开发者

Precision error using NSNumberFormatter numberFromString

Why does the following code produce "numberFromString = 9.390000000000001" rather than "numberFromString = 9.39"?

NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
[numFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numFormatter setPositiveFormat:@"$##0.00"];
[开发者_Python百科numFormatter setNegativeFormat:@"-$##0.00"];
NSNumber *nTCA = [numFormatter numberFromString:@"$9.39"];

NSLog(@"numberFromString = %@", nTCA);

I get the above results on OS X 10.6 and iOS 4.3.3.

What's the best way to correct this error?

Thanks


I suspect you are running into an error as a result of using floating-point precision. The way to fix this is to use NSDecimalNumber instead of NSNumber. There's a great post about this here.

NSDecimalNumber has a + decimalNumberWithString: method. Would that suffice for your purposes?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜