Created
September 17, 2013 04:03
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.