Ravi Srinivas

Greenhorn

Posts: 26

posted 12 years ago

Hi,

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).

Thanks,

Ravi

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).

Thanks,

Ravi

Nigel Browne

Ranch Hand

Posts: 704

posted 12 years ago

[ June 16, 2005: Message edited by: Nigel Browne ]

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 ]

Philip Heller

author

Ranch Hand

Ranch Hand

Posts: 119

posted 12 years ago

I read somewhere that doing floating-point arithmetic is like moving a pile of sand: every time you do it, you lose a little sand and you pick up a little dirt.

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.

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.

Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".

Steven Bell

Ranch Hand

Posts: 1071

Ravi Srinivas

Greenhorn

Posts: 26

posted 12 years ago

Thanks guys, for pointing me to BigDecimal. Here's how it worked out-

The output-

c= 0.38515595199999997

BDc= 0.385155952

The output-

c= 0.38515595199999997

BDc= 0.385155952