How to compare two double values in Java?

后端 未结 7 1364
滥情空心
滥情空心 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 13:55

    Basically you shouldn't do exact comparisons, you should do something like this:

    double a = 1.000001;
    double b = 0.000001;
    double c = a-b;
    if (Math.abs(c-1.0) <= 0.000001) {...}
    

提交回复
热议问题