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

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

    the correct way to test floats for 'equality' is:

    if(Math.abs(sectionID - currentSectionID) < epsilon)
    

    where epsilon is a very small number like 0.00000001, depending on the desired precision.

提交回复
热议问题