Invalid decimal separator with NSDecimalNumber in iOS

I tried to output a decimal description with the correct decimal separator as follows:

NSString* strValue = @"9.94300"; NSDecimalNumber* decimalNumber = [NSDecimalNumber decimalNumberWithString: strValue]; NSLocale* locale = [NSLocale currentLocale]; NSLog(@"%@", [locale localeIdentifier]); NSLog(@"%@", [decimalNumber descriptionWithLocale: locale] ); 

Output:

 de_DE 9.943 

The decimal separator must be ',' instead of '.' for this language. Where is the mistake? How can I infer the correct decimal separator depending on the local?

+4
source share
2 answers

@TriPhoenix: Yes, I am running iOS 5.

@Vignesh: Thank you very much. The following code works now if I install the iPhone language in German:

 NSString* strValue = @"9.94300"; NSDecimalNumber* decimalNumber = [NSDecimalNumber decimalNumberWithString: strValue]; NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init]; [numberFormatter setFormatterBehavior: NSNumberFormatterBehavior10_4]; [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle]; NSLog(@"%@", [numberFormatter stringFromNumber: decimalNumber] ); 

Output: 9943

But now I have a different problem. If I switch the iPhone language to English, the output will be 9.943 instead of 9.943. Am I doing something wrong?

+3
source

You can use this:

 NSLocale *locale = [NSLocale currentLocale]; float r = 50/100; NSString *str = [NSString stringWithFormat:@"%.2f%%", r]; str = [str stringByReplacingOccurrencesOfString:@"." withString:[locale objectForKey: NSLocaleDecimalSeparator]]; 

It worked!

+1
source

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


All Articles