Converting a String to a Double or Float can be easily achieved by using the if let statement in Swift. Take a look at the following example:
var string = "12.2416"
if let floatValue = Float(string) {
print("Float value = \(floatValue)")
} else {
print("String does not contain Float")
}
If the String contains a valid floating point value, then Swift will assign it to the floatValue constant which will be available within the if let scope. The result of this example will be printed as “Float value = 12.2416”.
As expected, in order to convert the String to a Double, substitute the Float() initializer with Double() initializer in the example above.
When would you use Double over Float data type? It all comes down to how big of a number you’re expecting the string to hold. Double represents a 64-bit floating point number and Float represents 32-bit number so if you’re expecting huge numbers, use Double.
If you’d like to learn how to round the value of floating point number to a desired decimal place and convert it to string, then check out our floating point precision in Swift String tutorial.
Related tutorials:
- How to pick a random element from an array in Swift
- How to make HTTP PUT request with JSON as Data in Swift