convert string to double

I want to convert a number (with a comma separating 1000s) such as 1,220 to a decimal. Without the comma I am just doing

[numberString doubleValue]


Is there a simple NSNumberFormater to have it recognize the comma as part of the number and not a "character" so the answer I get is 1220?


I used this:


myNewString = [myNewString stringByReplacingOccurrencesOfString:@"," withString:@""];

quote = [myNewString doubleValue];


Is this the best way? Is there another cleaner method?

There is a way without Formatter


let num = "1,220"
let strippedNum = num.replacingOccurrences(of: ",", with: "")
let val = Double(strippedNum)



with formatter, you have to use numberStyle


let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
formatter.locale = Locale(identifier: "en_US") // not needed if current is en_US
let val2 = formatter.number(from: num)

I think your approach is quite logical and optimal. Treat a string "1,210" like a string and delete the offending "," character as you would delete any character in a string. If you want to reinsert a character in a number then use an NSNumberFormatter.

The value of Formatter vs "brut force change" is to better localize.

convert string to double
 
 
Q