Reputation: 2593
I want to format floating point number into this 3,535,816.85
format. I have used NSNumberFormatter
for this.
Here is my code,
NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:13]; // Set this if you need 2 digits
NSString * newString = [formatter stringFromNumber:[NSNumber numberWithFloat:floatPSPercentage]];
However, I am not getting the expected result. What am I missing?
Upvotes: 0
Views: 438
Reputation: 155
You can use
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
to get such a format.You also need to set
[formatter setCurrencySymbol:@""];
if you don't want the $ symbol to be added in your NSString.
Upvotes: 0
Reputation: 15410
You can use specific initialization code as in iDeveloper's answer, but be wary: number formatting is culture-sensitive (although iDeveloper's answer does have some culture awareness as it takes the grouping separator from the current locale... but hardcoding other aspects means that you don't actually end up with the correct format for all locales).
A safer approach is to consider what kind of context your number applies to, and take the locale's default as-is. I.e. if it's to show a price, set the number style to NSNumnerFormatterCurrencyStyle. Otherwise you probably should just set it to NSNumberFormatterDecimalStyle.
Edit: Just noticed that your variable is named floatPSPercentage, so if what you are intending to display is a percentage, you'll get the correct format for the current locale by picking NSNumberFormatterPercentStyle, i.e. just replace the two lines in the middle of your snippet with:
[formatter setNumberStyle: NSNumberFormatterPercentStyle];
Upvotes: 0
Reputation: 852
Try this code:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *groupingSeparator = [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];
[formatter setGroupingSeparator:groupingSeparator];
[formatter setGroupingSize:3];
[formatter setAlwaysShowsDecimalSeparator:NO];
[formatter setUsesGroupingSeparator:YES];
as you can see Here.
Upvotes: 1