What's wrong with using == to compare floats in Java?

后端 未结 21 1954
你的背包
你的背包 2020-11-22 01:00

According to this java.sun page == is the equality comparison operator for floating point numbers in Java.

However, when I type this code:



        
21条回答
  •  遥遥无期
    2020-11-22 01:42

    Floating point values can be off by a little bit, so they may not report as exactly equal. For example, setting a float to "6.1" and then printing it out again, you may get a reported value of something like "6.099999904632568359375". This is fundamental to the way floats work; therefore, you don't want to compare them using equality, but rather comparison within a range, that is, if the diff of the float to the number you want to compare it to is less than a certain absolute value.

    This article on the Register gives a good overview of why this is the case; useful and interesting reading.

提交回复
热议问题