How to test if a double is zero?

前端 未结 5 1002
别跟我提以往
别跟我提以往 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 18:59

    Yes, it's a valid test although there's an implicit conversion from int to double. For clarity/simplicity you should use (foo.x == 0.0) to test. That will hinder NAN errors/division by zero, but the double value can in some cases be very very very close to 0, but not exactly zero, and then the test will fail (I'm talking about in general now, not your code). Division by that will give huge numbers.

    If this has anything to do with money, do not use float or double, instead use BigDecimal.

提交回复
热议问题