How to compare two double values in Java?

后端 未结 7 1528
滥情空心
滥情空心 2020-11-22 13:10

A simple comparison of two double values in Java creates some problems. Let\'s consider the following simple code snippet in Java.

package doublecomparision;         


        
7条回答
  •  被撕碎了的回忆
    2020-11-22 14:02

    Consider this line of code:

    Math.abs(firstDouble - secondDouble) < Double.MIN_NORMAL
    

    It returns whether firstDouble is equal to secondDouble. I'm unsure as to whether or not this would work in your exact case (as Kevin pointed out, performing any math on floating points can lead to imprecise results) however I was having difficulties with comparing two double which were, indeed, equal, and yet using the 'compareTo' method didn't return 0.

    I'm just leaving this there in case anyone needs to compare to check if they are indeed equal, and not just similar.

提交回复
热议问题