As others have already mentioned, you should use java.math.BigDecimal instead of float / double. However, this is due to its own set of problems.
For example, when you call BigDecimal (double), the value you pass will expand to the full view:
BigDecimal oneTenth = new BigDecimal(0.1); BigDecimal oneMillion = new BigDecimal(1000000); oneTenth.multiply(oneMillion) out> 100000.0000000000055511151231257827021181583404541015625000000
But when you use the constructor of BigDecimal (String), the eact value is displayed, and you get
BigDecimal oneTenth = new BigDecimal("0.1"); BigDecimalr oneMillion = new BigDecimal(1000000); oneTenth.multiply(oneMillion) out> 100000.0
You can learn more about the BigDecimal limitations in Joshua Bloch and Neal Gafter for the excellent Java puzzlers and this informative article. Finally, note that toString in BigDecimal will print in scientific notation, so you will need to use toPlainString .
Lars tackmann
source share