I have read a few questions about flaoting point numbers and their math. To me it looks like the issues only happen at greater scales (i.e. 10+ decimals). Now my issue happens at 2 decimals already and its quite big off in a few cases:
Following code:
System.out.println(
String.format("%.2f", BigDecimal.valueOf(2.8).divide(BigDecimal.valueOf(3.87), 2).doubleValue()));
System.out.println(
String.format("%.2f", BigDecimal.valueOf(2.41).divide(BigDecimal.valueOf(2.73), 2).doubleValue()));
generates this output respectively:
0.80
0.89
If I perform the calculations by hand (using google calculations), I get these results:
0.72351421188
0.88278388278
for the first calculations the results are really big (~0.08 off) while for the second one its very low (~0.01 off).
Is there some sane explanation as to why thie first result is that big? Or any way to get the right result using BigDecimal?
Note that
System.out.println(2.8/3.87);
actually returns the right result (0.7235142118863048).
Please also note that the String.format stuff is only used to check if the result was changed by it which is not the case. BigDecimal.valueOf(2.8).divide(BigDecimal.valueOf(3.87), 2).doubleValue() yields exactly the same result.