0

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?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Madhu
  • 2,565
  • 2
  • 25
  • 32
  • "float" will most definitely not give you the precision that you want. Use double. As a rule, use double and not float unless you have a specific reason that you can defend why you want to use float. – gnasher729 Apr 14 '14 at 11:13

3 Answers3

1

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.

Community
  • 1
  • 1
pankaj asudani
  • 862
  • 6
  • 18
0

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.

Parvendra Singh
  • 965
  • 7
  • 19
Cl3ment
  • 155
  • 4
0

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];
Clafou
  • 15,250
  • 7
  • 58
  • 89