To convert a string to float in Swift, you can use the 'Float()' initializer.
In this example,
str1
with a value of "3.14"
.Float()
initializer to convert the string to a float and store the result in a variable float1
.float1
.// Convert "3.14" String to Float
let str1: String = "3.14"
if let float1 = Float(str1) {
print("Float value is: \(float1)")
}
Float value is: 3.14
In this example,
str2
with a value of "10.5"
.Float()
initializer to convert the string to a float and store the result in a variable float2
.float2
.// Convert "10.5" String to Float
let str2: String = "10.5"
if let float2 = Float(str2) {
print("Float value is: \(float2)")
}
Float value is: 10.5
In this tutorial, we learned How to convert String to Float in Swift language with well detailed examples.