Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 760
jbehrens94 Avatar asked Jan 22 '16 09:01

jbehrens94


1 Answers

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

like image 108
luk2302 Avatar answered Oct 09 '22 23:10

luk2302