Separate number with commas after 3 digits white managing decimal places on a string iOS

597 views Asked by At

I have following variables

NSString* balance = @"43243534.4535345"
int decimalPoint = 2;

How can we place commas after three digits while managing decimal point according to given variable at same time. It's easy to do these action separately but how can we perform them together so result should be: 43,243,534.45

1

There are 1 answers

2
Artem Novichkov On

You can use NSNumberFormatter:

double number = 43243534.4535345;
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
numberFormatter.maximumFractionDigits = 2;
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *numberString = [numberFormatter stringFromNumber:@(number)];
NSLog(@"%@", numberString); 
//43,243,534.45 in log

in Swift:

let number = 43243534.4535345
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
formatter.numberStyle = .decimal
let formattedString = formatter.string(from: NSNumber(value: number))