I am making a very simple beginner project where I receive the data from a textField and store it in a Double var. I have tried the .toDouble() but it doesn´t seem to exist. Any help please?
Asked
Active
Viewed 1.4k times
4 Answers
5
You can simply put the string in as a parameter when creating a double!
let double = Double(textView.text!)

Izaak Prats
- 159
- 1
- 8
-
@RMenke it depends on the Xcode version but Xcode7 it is ok – Leo Dabus Nov 14 '15 at 04:11
-
@LeoDabus You are right, but it returns an optional. That is why I don't use it. My Bad :) – R Menke Nov 14 '15 at 04:13
-
1@RMenke just add the nil coalescing operator ?? 0 – Leo Dabus Nov 14 '15 at 04:19
5
Add the following extension and use .toDouble()
extension String {
func toDouble() -> Double? {
return NSNumberFormatter().numberFromString(self)?.doubleValue
}
}
Like
var someString = “30.23"
var someDouble = someString.toDouble()

Vakas
- 6,291
- 3
- 35
- 47
2
extension String {
var doubleValue: Double {
return Double(self) ?? 0
}
}
Usage:
let inputString = "32.1"
let myDouble = inputString.doubleValue // 32.1

Leo Dabus
- 229,809
- 59
- 489
- 571
0
if let doubleValue = Double(textView.text!) {
} else {
print("Not a valid number: \(textView.text!)")
}

Rabindra Nath Nandi
- 1,433
- 1
- 15
- 28