Why is BigDecimal returning a weird value?

前端 未结 6 632
花落未央
花落未央 2021-01-04 02:59

I am writing code that will deal with currencies, charges, etc. I am going to use the BigDecimal class for math and storage, but we ran into something weird with it.

6条回答
  •  滥情空心
    2021-01-04 03:58

    You are right, BigDecimal should be storing it correctly, my best guess is:

    • BigDecimal is storing the value correctly
    • When passed to a string formatting function, BigDecimal is being cast as a lower precision floating point value, creating the ...02.
    • When compared directly with a float, the float has an extra decimal place far beyond the 20 you see (classic floats can't be compared behavoir).

    Either way, you are unlikely to get accurate results comparing a float to a BigDecimal.

提交回复
热议问题