Andreas Grauel
Andreas Grauel

Reputation: 155

Converting an NSString to a locale specific NSNumber

I am using the KeyboardType = UIKeyboardTypeDecimalPad and on some Phones you see an "," on the bottom left instead of an ".". It depends on the language settings of the phone! With the "." version everything works fine when i use [NSNumber numberWithFloat:[textField.text floatValue]] but with the "," version it says 2.0 for 2,5. Does anybody knows a work around?

Upvotes: 4

Views: 1888

Answers (2)

vikas kumar jangir
vikas kumar jangir

Reputation: 1

NSNumberFormatter *numberFormatter = [NSNumberFormatter new];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[numberFormatter setLocale:usLocale];
NSNumber *num = [numberFormatter numberFromString:textField.text];

You can set the locale to us and always use the . annotation number.

Upvotes: 0

Nick Moore
Nick Moore

Reputation: 15857

You need to do a local-aware string conversion which treats "2.5" and "2,5" correctly according to the default locale. Try:

NSNumber *num=[NSDecimalNumber decimalNumberWithString:textField.text];

From NSDecimalNumber Class Reference:

Whether the NSDecimalSeparator is a period (as is used, for example, in the United States) or a comma (as is used, for example, in France) depends on the default locale.

Upvotes: 6

Related Questions