user1903992
user1903992

Reputation: 465

Separate number with commas on a string iOS

I have an NSInteger (say with value 60000), when I convert it to string however, I want to get "60,000" instead of "60000". Is there some method to do it? Thanks.

Upvotes: 8

Views: 5305

Answers (4)

Vineet Singh
Vineet Singh

Reputation: 4019

Use the NSNumberFormatter for formatting numeric data to a localized string representation.

int aNum = 60000;
NSString *display = [NSNumberFormatter localizedStringFromNumber:@(aNum)
                                                     numberStyle:NSNumberFormatterCurrencyStyle];

On doing this,you will get '$60,000.00'

after that,you can remove the sign of $ and '.'(decimal) by doing this..

 NSString *Str = [display stringByReplacingOccurrencesOfString:@"$" withString:@""];

 NSString *Str1 = [Str stringByReplacingOccurrencesOfString:@"." withString:@""];

NSString *newString = [Str1 substringToIndex:[Str1 length]-1];

NSString *newString1 = [newString substringToIndex:[newString length]-1];

'newString1' will give you the required result.

Upvotes: -1

Andrew Tetlaw
Andrew Tetlaw

Reputation: 2689

You can use a number formatter:

NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
NSString *numberString = [numberFormatter stringFromNumber: [NSNumber numberWithInteger: i]];

Upvotes: 3

Anusha Kottiyal
Anusha Kottiyal

Reputation: 3905

Try this,

NSString *numString = [NSString stringWithFormat:@"%d,%d",num/1000,num%1000];

Upvotes: 2

rmaddy
rmaddy

Reputation: 318794

Use a number formatter:

NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
[fmt setNumberStyle:NSNumberFormatterDecimalStyle]; // to get commas (or locale equivalent)
[fmt setMaximumFractionDigits:0]; // to avoid any decimal

NSInteger value = 60000;

NSString *result = [fmt stringFromNumber:@(value)];

Upvotes: 19

Related Questions