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?
精彩评论