Java: Double Value Comparison

后端 未结 7 2156
日久生厌
日久生厌 2020-12-01 12:33

Do we need to be careful when comparing a double value against zero?

if ( someAmount <= 0){
.....
}
7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 12:59

    Check a double or float value is 0, an error threshold is used to detect if the value is near 0, but not quite 0. I think this method is the best what I met.

    How to test if a double is zero? Answered by @William Morrison

    public boolean isZero(double value, double threshold){
      return value >= -threshold && value <= threshold;
    }
    

    For example, set threshold as 0. like this,

    System.out.println(isZero(0.00, 0));
    System.out.println(isZero(0, 0));
    System.out.println(isZero(0.00001, 0));
    

    The results as true, true and false from above example codes.

    Have Fun @.@

提交回复
热议问题