Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Multiplying double values  RSS feed

 
Ravi Srinivas
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 704
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use BigDecimal.
 
Ravi Srinivas
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys, for pointing me to BigDecimal. Here's how it worked out-



The output-
c= 0.38515595199999997
BDc= 0.385155952
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!