I'm trying to write a BMI program in swift language. And I got this problem: how to convert a String to a Double?
In Objective-C, I can do like this:
double myDouble = [myString doubleValue];
But how can I achieve this in Swift language?
I'm trying to write a BMI program in swift language. And I got this problem: how to convert a String to a Double?
In Objective-C, I can do like this:
double myDouble = [myString doubleValue];
But how can I achieve this in Swift language?
Swift 4.2+ String to Double
You should use the new type initializers to convert between String and numeric types (Double, Float, Int). It'll return an Optional type (Double?) which will have the correct value or nil if the String was not a number.
Note: The NSString doubleValue property is not recommended because it returns 0 if the value cannot be converted (i.e.: bad user input).
Unwrap the values to use them using if/let
You can convert formatted numbers and currency using the
NumberFormatter
class.Currency formats
Read more on my blog post about converting String to Double types (and currency).
SWIFT 3
To clear, nowadays there is a default method:
public init?(_ text: String)
ofDouble
class.It can be used for all classes.
let c = Double("-1.0")
let f = Double("0x1c.6")
let i = Double("inf")
, etc.I haven't seen the answer I was looking for. I just post in here mine in case it can help anyone. This answer is valid only if you don't need an specific format.
Swift 3
Use this code in Swift 2.0
let strWithFloat = "78.65" let floatFromString = Double(strWithFloat)
1.
2.
May be this help for you.