I need to multiply some decimal values with accuracy. For e.g. 1.64456 * 0.2342. I'm using double to store these numbers, but the result of multiplying them is 0.38515595199999997 instead of the expected 0.385155952.
How do I get the exact value? (the exact number of digits after the decimal point in the input is not known).
Quote from: Java theory and practice: Where's your point? by Brian Goetz
Don't use floating point numbers for exact values
Some non-integral values, like dollars-and-cents decimals, require exactness. Floating point numbers are not exact, and manipulating them will result in rounding errors. As a result, it is a bad idea to use floating point to try to represent exact quantities like monetary amounts. Using floating point for dollars-and-cents calculations is a recipe for disaster. Floating point numbers are best reserved for values such as measurements, whose values are fundamentally inexact to begin with.
[ June 16, 2005: Message edited by: Nigel Browne ]
If your values are within a decent limited range, you could do something like the following, to use integer rather than floating arithmetic:
This prints out
c = 0.38515595199999997, cNormalized = 0.385155952
For more precise inputs, you need to multiply by something bigger than a million.
If this trick doesn't work, check out java.math.BigDecimal.