0

I am writing mathematical function using Java and when I try to compare my result with ms office excel formula function the accuracy of the both the values missing which make my comparison(==) fails in case of double values.

My result:
2.3450414545545569404E16

MS excel result:
2.34504145455455694E16

I did some research on it and found few links but it doesn't solve my issue and I can't use the Big decimal as it won't be consistent to my end result.

I couldn't understand why my function shows extra values (404E16) and how it can be formatted to produce output like (2.34504145455455694E16)

Community
  • 1
  • 1
user492888
  • 207
  • 3
  • 17

4 Answers4

2

use strictfp in your method. That may solve accuracy problems.

This link provides more information on strictfp.

Keerthivasan
  • 12,760
  • 2
  • 32
  • 53
1

If BigDecimal is not an option, this is a good way to compare double values:

https://stackoverflow.com/a/8081911/3115739

Community
  • 1
  • 1
nillas
  • 431
  • 3
  • 4
0

You can compare while ignoring the last digits:

boolean equals = Math.abs(myResult - msExcelResult) < 1
Codev
  • 1,040
  • 2
  • 14
  • 31
  • Thanks @Codev I tried it and it worked but another problem is I need to maintain consistency between my result and excel result(i.e both should be excatly same).So is there a way to format the my result(2.3450414545545569404E16) like ms result(2.34504145455455694E16) or should I need to follow any standards for double values? – user492888 Dec 27 '13 at 09:10
0

If the issue is just a formatting one you just need to use an appropriate format string to output the number. Quite what to use depends on exactly how you are outputting the number but things like DecimalFormat, format strings (System.out.format), etc will all help you.

http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

Tim B
  • 40,716
  • 16
  • 83
  • 128