How to test if a double is zero?

前端 未结 5 992
别跟我提以往
别跟我提以往 2020-12-08 18:32

I have some code like this:

class Foo {
    public double x;
}

void test() {
    Foo foo = new Foo();

    // Is this a valid way to test for zero? \'x\' ha         


        
5条回答
  •  一整个雨季
    2020-12-08 19:02

    Numeric primitives in class scope are initialized to zero when not explicitly initialized.

    Numeric primitives in local scope (variables in methods) must be explicitly initialized.

    If you are only worried about division by zero exceptions, checking that your double is not exactly zero works great.

    if(value != 0)
        //divide by value is safe when value is not exactly zero.
    

    Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0.

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

提交回复
热议问题