1

Converting a string to a double in Swift is done as follows:

var string = "123.45"
string.bridgeToObjectiveC().doubleValue

If string is not a legal double value (ex. "a23e") the call to doubleValue will return 0.0. Since it is not returning nil how am I supposed to discriminate between the legal user input of 0.0 and an illegal input?

Sterbic
  • 213
  • 5
  • 15

3 Answers3

1

This is not a problem that is specific to Swift, With NSString in Objective-C, the doubleValue method returns 0.0 for invalid input (which is pretty horrible!). You are going to have to check the format of the string manually.

See the various options available to you here:

Check that a input to UITextField is numeric only

Community
  • 1
  • 1
ColinE
  • 68,894
  • 15
  • 164
  • 232
1

Here is my solution. Try to parse it and if it's not nil return the double value, otherwise handle it how you want.

var string = "2.1.2.1.2"
if let number = NSNumberFormatter().numberFromString(string) {
    return number.doubleValue
} else {
    ...
}
louis1204
  • 401
  • 1
  • 7
  • 21
0

Here is the solution I would use:

var string = NSString(string:"string")
var double = string.doubleValue
if double == 0.0 && string == "0.0"
{
    //double is valid
}
else
{
    //double is invalid
}

Firstly, I couldn't reassign the double value of the string to the original string variable, so I assigned it to a new one. If you can do this, assign the original string variable to a new variable before you convert it to a double, then use the new variable in place of string in the second if statement, and replace double with string the first statement.

The way this works is it converts the string to a double in a different variable, then it checks to see if the double equals 0.0 and if the original string equals 0.0 as a string. If they are both equal, the double is valid, as the user originally input 0.0, if not, the double is invalid. Put the code you want to use if the double is invalid in the else clause, such as an alert informing the user their input was invalid.

trumpeter201
  • 8,487
  • 3
  • 18
  • 24