If we have an integer value say 123456789 to display the price of some commodity and we need to display it in the format like 123,456,789 then we can use NSNumberFormatter and then set its number style.
NSNumberFormatter has the following number Styles:
kCFNumberFormatterNoStyle, kCFNumberFormatterDecimalStyle, kCFNumberFormatterCurrencyStyle, kCFNumberFormatterPercentStyle, kCFNumberFormatterScientificStyle, kCFNumberFormatterSpellOutStyle.
We can set the above number styles as per our requirement.
For the above specified requirement we can use kCFNumberFormatterDecimalStyle, NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setNumberStyle:kCFNumberFormatterDecimalStyle]; NSString *formattedString = [formatter stringFromNumber:[NSNumber numberWithInt:123456789]]; NSLog(@"%@", formattedString);
This will print in the console:
123,456,789
At some places we would like to have the above integer in the format: 12,34,56,789
For this we just need to add one more line in the above code:
[formatter setSecondaryGroupingSize:2]
This will give the output in the form: 12,34,56,789.
Similarly we can set other number styles to display our integer in various formats.