reinaldoluckman
reinaldoluckman

Reputation: 6348

NSNumberFormatter bug?

When I try to convert the NSString @"8.8" to a NSNumber by NSNumberFormatter

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
[formatter setPositiveFormat:@"###0.##"];

NSNumber *result = [formatter numberFromString:@"8.8"];
NSLog(@"%@", [result stringValue]);
[formatter release];

the result is 8.800000000000001.

For any other value (i.e: 6.6, 7.7, 9.9, 1.2, 4.7 etc.), the logged result was exactly the same NSString passed to numberFromString method.

I'm using XCode 4.1 and the 4.3 simulator. There is no difference if I put (or not) setMaximumFractionDigits or/and setPositiveFormat, the result is always 8.800000000000001. What is happening?

Upvotes: 0

Views: 258

Answers (1)

zaph
zaph

Reputation: 112857

Most numbers that are not integers can not be represented accurately in floating point variables. There is a class NSDecimalNumber that handles exact values at a cost of overhead, this is mainly used for monetary calculations.

See: WIkipedia:
Floating point numbers are rational numbers because they can be represented as one integer divided by another. The base however determines the fractions that can be represented. For instance, 1/5 cannot be represented exactly as a floating point number using a binary base but can be represented exactly using a decimal base.

Upvotes: 4

Related Questions