Skip to content

Instantly share code, notes, and snippets.

@bagelturf
Created September 17, 2013 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bagelturf/6589962 to your computer and use it in GitHub Desktop.
Save bagelturf/6589962 to your computer and use it in GitHub Desktop.
Using NSNumberFormatter to read in decimal numbers has rounding problems. However decimalNumberWithString can't grok currency symbols, so I'm using NSNumberFormatter.
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
NSNumberFormatter *inputFormatter = [[NSNumberFormatter alloc] init];
[inputFormatter setLocale:locale];
[inputFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[inputFormatter setLenient:YES];
[inputFormatter setGeneratesDecimalNumbers:YES];
NSDecimalNumber *a = (NSDecimalNumber *)[inputFormatter numberFromString:@"87.85"];
NSDecimalNumber *b = [NSDecimalNumber decimalNumberWithString:@"87.85"];
NSString *pa = [a descriptionWithLocale:locale];
NSString *pb = [b descriptionWithLocale:locale];
NSLog(@"%@",pa); // prints 87.84999999999999
NSLog(@"%@",pb); // prints 87.85
@mackuba
Copy link

mackuba commented Nov 5, 2013

Just out of curiosity, have you found a way to convince NSNumberFormatter to actually generate decimal numbers without going through floats in between? I'm having the same problem... I don't want to use decimalNumberWithString because the decimal separator symbol might be different depending on locale.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment