Search code examples
objective-ciosnsstringnsnumbernsnumberformatter

Converting NSString to NSNumber results in too many digits and strange rounding


When converting an NSString, which contains standard decimal numbers with two digits (e.g. 8.20) to a NSNumber, I get (from time to time) extra digits and a strange rounding behavior when logging the result via NSLog or saving it in Core Data (as float or double), e.g. 8.20 -> 8.199999999999999.

This is the code I am using to convert the numbers:

 NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
 [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
 [numberFormatter setMaximumFractionDigits:5];
 NSNumber *num = [numberFormatter numberFromString:str];

I do not understand why the conversion to NSNumber messes the number up. What is wrong with my code?


Solution

  • This is just how float and double behaves in C/Objective-C (and many other languages). For example, when you type into python 8.0, the result would be 8.000000000001. I recommend using NSScanner to convert them into primitive number types (double, float).