Double precision multiplication accuracy in java?

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

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

+6
source share
3 answers

Multiplication works fine, but 2.2 cannot be represented exactly as double. Nearest doubles:

  • 2.199999999999999733 (0x400199999999999999)
  • 2.200000000000000177 (0x40019999999999999a)

Some software will print the last value as 2.2 , but this does not mean that it is accurate. It just means that it is considered "close enough."

+6
source

If you work with financial data, do not use float or double , just use java.math.BigDecimal

+3
source

you can use BigDecimal, but be sure to use the BigDecimal (String) construct, not the BigDecimal (double) construct. The difference between them:

enter image description here

+1
source

Source: https://habr.com/ru/post/891239/


All Articles