4

I tried to output the description of a decimal number with the correct decimal separator in the following way:

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

The output is:

de_DE
9.943

The decimal separator should be ',' instead of '.' for this locale. Where is the error? How can I output the correct decimal separator depending on the local?

Waterman
  • 131
  • 3
  • 11
  • look at this http://stackoverflow.com/a/3949169/641062 – Vignesh Feb 01 '12 at 09:58
  • Very puzzeling. I assume you're running iOS 5 (where I could reproduce this)? In the 4.3 emulator the code runs fine and outputs 9,943 as expected. This might even be a bug... – Dennis Bliefernicht Feb 01 '12 at 12:19
  • 1
    Addition: NSNumber does the right thing while NSDecimalNumber does not on iOS 5. Filing a bug report now ;-) [maybe NSNumber is an alternative for you?] – Dennis Bliefernicht Feb 01 '12 at 12:25

2 Answers2

3

@TriPhoenix: Yes I'm running iOS 5.

@Vignesh: Thank you very much. The following code works now if I set the iPhone language to 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] );

The output is: 9,943

But now I have another problem. If I switch the iPhone language back to English the output is still 9,943 instead of 9.943. Do I make something wrong?

Waterman
  • 131
  • 3
  • 11
  • Anyone that could help, please? – Waterman Feb 03 '12 at 13:11
  • You want to set "Regional Setting" to German to obtain the comma, not the Language – Olaf Feb 03 '12 at 14:23
  • I want to output the decimal separator of the number depending on the language of the iPhone, i.e., '9,943' if the iPhone is set to German, '9.943' if the iPhone is set to English. – Waterman Feb 03 '12 at 15:47
  • 1
    There are two settings in the iPhone: The "Regional Settings" controls date and number format. The "Language" controls what words are used. – Olaf Feb 03 '12 at 17:19
  • That solved it. Sorry, I'm a newbie on iPhone and didn't noticed this second setting. Many thanks, Olaf. – Waterman Feb 06 '12 at 06:56
1

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!

Mike
  • 11
  • 1