Billo
Billo

Reputation: 21

NSNumber and intValue: weird behavior

I'm a noob with Obj-C, but today I'm experiencing something I really can't understand on my own with NSNumber and intValue.

I have this example code:

    double quota = 203/100.0;    
    NSLog(@"%f %f %@ %d",
    quota,
    quota*100.0,
    [NSNumber numberWithDouble:(quota*100.0)],
    [ [NSNumber numberWithDouble:(quota*100.0)] intValue]
);

which prints the output:

2.030000 203.000000 203 202

Please can someone help me to understand why the final intValue turns the 203 in 202? I feel like I'm missing something really obvious and important.

TIA

Upvotes: 2

Views: 1148

Answers (1)

Joe
Joe

Reputation: 57179

I ran your code and the result of 203/100.0 = 2.0299999999999998 while stored as a double. It looks like NSNumber as well as %f is rounding it to 2.03 when printing it but when you get the int value for 202.99999999999998 the .99999999999998 is being dropped. Hopefully someone (or my self with an edit) can add to why this rounding behavior is occurring when printing the double value.

Upvotes: 4

Related Questions