user291701 user291701 - 23 days ago 8
Java Question

How to test if a double is zero?

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' hasn't been set to anything yet.
if (foo.x == 0) {

}

foo.x = 0.0;

// Will the same test be valid?
if (foo.x == 0) {

}
}


I basically want to avoid a divide-by-zero exception in the future.

Thanks

Answer

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;
}
Comments