9

What is the guaranteed accuracy of multiplication operator for double values in java?

For example, 2.2 * 100 is 220.00000000000003, but 220 is a double number. 220.00000000000003 is the next double after 220.

ililit
  • 1,309
  • 1
  • 12
  • 19
  • 1
    daba: it depends on the numbers your multiplicating, seen how floating-point numbers are implemented in Java (and in most languages). Floating-point numbers in Java are mostly IEEE-754. I suggest the fascinating following read: *"What every computer scientist should know about floating-point numbers"* http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html Note the "scientist" in the name: if you're not doing scientifical computation, you're probably wrong if you use floating-point numbers. – SyntaxT3rr0r Jun 23 '11 at 19:28
  • related https://stackoverflow.com/questions/588004/is-floating-point-math-broken\ – Ahmed Nabil Jun 06 '23 at 12:03

3 Answers3

8

The multiplication is working fine, but 2.2 cannot be represented exactly as a double. The closest doubles are:

  • 2.199999999999999733 (0x4001999999999999)
  • 2.200000000000000177 (0x400199999999999a)

Some software will print the latter value as 2.2, but that doesn't mean it's exact. It just means it's treated as "close enough".

3

If you are working with financials data dont use float or double just use java.math.BigDecimal

Sergii Zagriichuk
  • 5,389
  • 5
  • 28
  • 45
  • You asked about multiple on double, try to do the same operation but just using BigDecimal, and your problem will be solved. – Sergii Zagriichuk Jun 23 '11 at 19:43
  • 1
    my question was about the accuracy of multiplication operation, as i have read in [What every computer scientist should know about floating-point numbers"](http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html) "The IEEE standard requires that the result of addition, subtraction, multiplication and division be exactly rounded. That is, the result must be computed exactly and then rounded to the nearest floating-point number (using round to even).", i was surprised to receive the answer i had not expected. @duskwuff explained below why this happened. – ililit Jun 23 '11 at 20:00
  • I have read it and know :), and it was just advice, but I understand you good point to read! – Sergii Zagriichuk Jun 23 '11 at 20:29
2

you can use BigDecimal, but make sure that you use the construct of BigDecimal(String) rather than BigDecimal(double). The difference between them is:

enter image description here

learner
  • 1,381
  • 1
  • 10
  • 16