Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use thousand separator in NSString

Tags:

ios

nsstring

NSString just like "1000.00" and "1008977.72",

how can I format them to "1,000.00" and "1,008,977.00"

That's my question, and help me with this, thank you in advance.

like image 419
jxdwinter Avatar asked Apr 11 '12 09:04

jxdwinter


1 Answers

I did that not a long age. Here's the code:

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setGroupingSeparator:@","];
[numberFormatter setGroupingSize:3];
[numberFormatter setUsesGroupingSeparator:YES];
[numberFormatter setDecimalSeparator:@"."];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
NSString *theString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:1008977.72]];

Hope it helps


EDIT

As Olie asked I'll post a code that will use current locale settings to set grouping/decimal separators itself.

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:[NSLocale currentLocale]];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
[numberFormatter setMaximumFractionDigits:2];
NSString *theString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:1008977.72]];
NSLog(@"The string: %@", theString);

Using [NSLocale localeWithLocaleIdentifier:] instead of [NSLocale currentLocale] gave me the following results:

[NSLocale localeWithLocaleIdentifier:@"be_NL"]
The string: 1 008 977,72
[NSLocale localeWithLocaleIdentifier:@"en_GB"]
The string: 1,008,977.72
[NSLocale localeWithLocaleIdentifier:@"DE"]
The string: 1.008.977,72
[NSLocale localeWithLocaleIdentifier:@"en_US"]
The string: 1,008,977.72
like image 108
Novarg Avatar answered Nov 16 '22 01:11

Novarg