KONG
KONG

Reputation: 7371

parse number from a locale specific string?

I have to get the number from France-number-style string: @"30.000,00" When I use NSNumberFormattern to parse

 NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
 NSNumber *priceNumberValue = [numberFormatter numberFromString:@30.000"];

It returned 30, my expected return is 30000 I try to use other options

NSLocale *vnLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"];
[numberFormatter setLocale:vnLocale];

or

[numberFormatter setDecimalSeparator:@","];

but it still returns unexpected value: 30

What is the correct way for me to tell the NSNumberFormatter parse @"30.000,00"?

Upvotes: 2

Views: 786

Answers (1)

Philippe Leybaert
Philippe Leybaert

Reputation: 171774

Setting the locale should work, but you'll have to tell the numberformatter to use the grouping separator:

[numberFormatter setUsesGroupingSeparator:YES];

If that doesn't work, the following will definitely work:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setDecimalSeparator:@","];
[numberFormatter setGroupingSeparator:@"."];
[numberFormatter setUsesGroupingSeparator:YES];
NSNumber *priceNumberValue = [numberFormatter numberFromString:@"30.000,00"];

After checking this, it seems that the "fr-FR" locale doesn't have the properties you expect. However, using the "fr-BE" locale works fine:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_BE"];
[numberFormatter setLocale:locale];
[locale release];
[numberFormatter setUsesGroupingSeparator:YES];
NSNumber *priceNumberValue = [numberFormatter numberFromString:@"30.000,00"];

Upvotes: 3

Related Questions