stringswift2doublensnumberformatter

Swift – String with comma-separator to double


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?


Solution

  • 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