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?

0

4 Answers 4

5

You can simply put the string in as a parameter when creating a double!

let double = Double(textView.text!)

Sign up to request clarification or add additional context in comments.

3 Comments

@RMenke it depends on the Xcode version but Xcode7 it is ok
@LeoDabus You are right, but it returns an optional. That is why I don't use it. My Bad :)
@RMenke just add the nil coalescing operator ?? 0
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()

Comments

2
extension String {
    var doubleValue: Double {
        return Double(self) ?? 0
    }
}

Usage:

let inputString = "32.1"
let myDouble = inputString.doubleValue   // 32.1

Comments

0
if let doubleValue = Double(textView.text!) {

} else {
    print("Not a valid number: \(textView.text!)")
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.