Floating point precision and equality in Java

后端 未结 1 1183
死守一世寂寞
死守一世寂寞 2021-01-29 05:14

It\'s know that floating point number, even those with fixed digits after decimal point in decimal format, can\'t be represented exactly. So I have the following program to test

相关标签:
1条回答
  • 2021-01-29 05:31
    1. I am suspicious of System.out.printf working correctly here. A reliable way to get the exact double value you get when you write 0.1 is to write new BigDecimal(0.1).toString().
    2. "Why does 0.1f + 0.2f == 0.3f return true?" Pretty much because you just got lucky: rounding 0.1 to the closest float representation and 0.2 to the closest float representation and adding them gets you the closest representable float to 0.3. That's not true in general, those values just happen to work.
    0 讨论(0)
提交回复
热议问题