Accuracy of double precision multiplication in java?

前端 未结 3 686
感动是毒
感动是毒 2021-01-18 05:36

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

相关标签:
3条回答
  • 2021-01-18 05:49

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

    0 讨论(0)
  • 2021-01-18 05:56

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

    0 讨论(0)
  • 2021-01-18 06:05

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

    0 讨论(0)
提交回复
热议问题