How to compute the double values in java with proper output?

171 views Asked by At

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)

4

There are 4 answers

1
Keerthivasan On

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

This link provides more information on strictfp.

1
Codev On

You can compare while ignoring the last digits:

boolean equals = Math.abs(myResult - msExcelResult) < 1
1
nillas On

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

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

0
Tim B On

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