1

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?

JuanEnriquez
  • 19
  • 1
  • 1
  • 3

4 Answers4

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
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