Novarg
Novarg

Reputation: 7440

NSString to NSNumber with some decimal separator

The app I'm building now has a possibility to "download" text files and get the numbers from there. In the simulator everything works perfectly, but when I tested it on a device it just crashed. After a while I figured out that the problem was with the decimal separators. In that file I used . and the local setting of my iPhone require ,. Example of that string:

Product 1;100.00
Product 2;82.85
Product 3;95.12
//etc...

After changing the the first few . into , I could successfully run the app till it reached the first ., so that's the problem.

I can easily replace all . into , programmatically, BUT I want this app to work in any country with any number format and not limit it to some specific market.

The code I was using to get these numbers:

NSString *fileContents = [[NSUserDefaults standardUserDefaults]objectForKey:theKey];
NSArray *allLinedStrings = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *allStringNormalized = [NSMutableArray array];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
for (int i = 0; i < allLinedStrings.count; i++) {
    NSString *bla = [allLinedStrings objectAtIndex:i];
    NSArray *bla1 = [bla componentsSeparatedByString:@";"];
    [allStringNormalized addObject:[formatter numberFromString:[bla1 objectAtIndex:1]]];
}
self.values = [NSArray arrayWithArray:allStringNormalized];

Any help would be appreciated.

Thank you :)

Upvotes: 0

Views: 1354

Answers (1)

freespace
freespace

Reputation: 16701

If I understand the problem correctly, you want NSNumberFormatter to always use . as the decimal separator, regardless of the phone's locale. The solution to this is simple: use the instance methods setDecimalSeparator: and setCurrencyDecimalSeparator: of NSNumberFormatter to set the decimal separator to ..

Note that you don't need to set both decimal separators. You use setDecimalSeparator: if your numberStyle is NSNumberFormatterDecimalStyle and setCurrencyDecimalSeparator: if your numberStyle is NSNumberFormatterCurrencyStyle.

See the documentation for more details.

Upvotes: 3

Related Questions