Swift – String with comma-separator to double

jbehrens94 picture jbehrens94 · Jan 22, 2016 · Viewed 8.1k times · Source

I have currently a string like this: "8,0" or "4,25" and I need to convert it to a Double, but how would I do that? Do I first replace the , with a .?

I have looked at NSNumberFormatter but that returned nil for every string.

let formatter = NSNumberFormatter()
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let grade = formatter.numberFromString(grade["Cijfer"].stringValue)
print(grade)

What should I use?

Answer

luk2302 picture luk2302 · Jan 22, 2016

Use the decimalSeparator:

let formatter = NSNumberFormatter()
formatter.decimalSeparator = ","
let grade = formatter.numberFromString("2,3")

if let doubleGrade = grade?.doubleValue {
    print(doubleGrade)
} else {
    print("not parseable")
}

Prints

2.3