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

后端 未结 21 1934
你的背包
你的背包 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:37

    As of today, the quick & easy way to do it is:

    if (Float.compare(sectionID, currentSectionID) == 0) {...}
    

    However, the docs do not clearly specify the value of the margin difference (an epsilon from @Victor 's answer) that is always present in calculations on floats, but it should be something reasonable as it is a part of the standard language library.

    Yet if a higher or customized precision is needed, then

    float epsilon = Float.MIN_NORMAL;  
    if(Math.abs(sectionID - currentSectionID) < epsilon){...}
    

    is another solution option.

提交回复
热议问题