How to convert the string to Double in Swift
In this tutorial, we are going to learn about how to convert the string to double in Swift.
Converting string to double
To convert a string to a double, we can use the built-in Double()
initializer syntax in Swift.
The Double()
initializer takes the string as an input and returns the double instance. If the string contains invalid characters or invalid format it returns nil.
Here is an example, that converts the string "13.344"
to Double:
let string = "13.344"
let myDouble = Double(string) ?? 0
print(myDouble)
Output:
13.344
Similarly, we can also use the following syntax to convert it.
import Foundation
let string = "13.344"
let myDouble = (string as NSString).doubleValue
print(myDouble)