Convert NSString to locale-specific NSNumber

I use KeyboardType = UIKeyboardTypeDecimalPad , and on some phones you see "," bottom left instead of ".". It depends on the language settings of the phone! WITH "." The version works fine when I use [NSNumber numberWithFloat: [textField.text floatValue]], but with the version “,” it says 2.0 for 2.5. Does anyone know a job?

+4
source share
2 answers

You need to perform string conversion in local mode, which will handle "2.5" and "2.5" correctly in accordance with the default locale. Try:

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

From Link to NSDecimalNumber Class :

Regardless of whether the NSDecimalSeparator period (as used, for example, in the USA) or a comma (used, for example, in France) depends on the default locale.

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

You can set the language for us and always use it. annotation number.

0
source

Source: https://habr.com/ru/post/1334337/


All Articles