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 (ie: 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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.