简体   繁体   English

NSNumberFormatter错误?

[英]NSNumberFormatter bug?

When I try to convert the NSString @"8.8" to a NSNumber by NSNumberFormatter 当我尝试通过NSNumberFormatter将NSString @"8.8"转换为NSNumber时

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 . 结果是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. 对于任何其他值(即: 6.67.79.91.24.7等等),记录的结果是完全一样的NSString传递给numberFromString方法。

I'm using XCode 4.1 and the 4.3 simulator. 我正在使用XCode 4.1和4.3模拟器。 There is no difference if I put (or not) setMaximumFractionDigits or/and setPositiveFormat , the result is always 8.800000000000001 . 如果我放置(或不放置) setMaximumFractionDigits或/和setPositiveFormat没有区别,则结果始终为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. 有一个NSDecimalNumber类,它会以开销为代价处理精确值,该类主要用于货币计算。

See: WIkipedia : 请参阅: 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. 例如,不能使用二进制基数将1/5精确地表示为浮点数,而可以使用十进制基数精确地表示1/5。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM