File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# Multiplying double values

Ravi Srinivas
Greenhorn

Joined: Sep 04, 2003
Posts: 26
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
Nigel Browne
Ranch Hand

Joined: May 15, 2001
Posts: 673
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

Joined: Oct 24, 2000
Posts: 119
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.

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

Joined: Dec 29, 2004
Posts: 1071
Use BigDecimal.
Ravi Srinivas
Greenhorn

Joined: Sep 04, 2003
Posts: 26
Thanks guys, for pointing me to BigDecimal. Here's how it worked out-

The output-
c= 0.38515595199999997
BDc= 0.385155952

I agree. Here's the link: http://aspose.com/file-tools

subject: Multiplying double values