NSNumberFormatter with comma decimal separator

I would recommend not hardcoding the separator to ensure the right separator behavior based on the iPhone locale setting. The easiest way to to this is:

using objective-c

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
numberFormatter.locale = [NSLocale currentLocale];// this ensures the right separator behavior
numberFormatter.numberStyle = NSNumberFormatterDecimalStyle;
numberFormatter.usesGroupingSeparator = YES;

// example for writing the number object into a label
cell.finalValueLabel.text = [NSString StringWithFormat:@"%@", [numberFormatter stringForObjectValue:numberFromString]]; // your var name is not well chosen

using SWIFT 3

 let formatter = NumberFormatter()
 formatter.locale = NSLocale.current // this ensures the right separator behavior
 formatter.numberStyle = NumberFormatter.Style.decimal
 formatter.usesGroupingSeparator = true

 // example for writing the number object into a label
 // your variable "numberFromString" needs to be a NSNumber object
 finalValueLabel.text = formatter.string(from: numberFromString)! // your var name is not well chosen

and I would not use the var-name “numberFromString” because it is an NSNumberFormatter method.
Good luck!

Leave a Comment