0

I'm dealing with an NSMutableArray of NSNumber and I ran into a weird bug. The [NSNumber doubleValue] (construct with double 0) seems to not to be equals to 0.0.

The bug appears in the simpliest function ever : the max function.

- (double) maxValY{
    double max = DBL_MIN;
    for (NSNumber *doubleNumber in arrayNumbers) {
            if (max<[doubleNumber doubleValue]){
                max = [doubleNumber doubleValue];
            }

    }

    NSLog(@"max %f",max);
    if(max <=0.0){
        NSLog(@"max is equal to 0");
        return 1;
    }else{
        NSLog(@"max is not equal to 0");
    }

    return max;
}

The console prints :

2013-01-02 11:27:56.208 myApp[1920:c07] max 0.000000
2013-01-02 11:27:56.210 myApp[1920:c07] max is not equal to 0
Alexandre
  • 410
  • 5
  • 21

1 Answers1

2

This isn't a bug: it's double precision. With floating point number what you see is not necessarily what you're getting. This question has some more information:

Why do I see a double variable initialized to some value like 21.4 as 21.399999618530273?

The easiest solution is going to be to cast to an integer, if all you care about is whether a number is equal or greater than zero. There are other alternatives that are more complex: the answer I've linked to has a few. The link someone gave you in the comments about floating point mathematics may also be helpful.

Community
  • 1
  • 1
lxt
  • 31,146
  • 5
  • 78
  • 83