Kotlin – Convert String to Float

Convert string to float in Kotlin

To convert a given string value to a float type value in Kotlin, you can use String.toFloat() function.

Call toFloat() function on the string value str.

str.toFloat()

The function returns a float value created from the content in String value.

Examples

Convert the string “6523” to float value

In the following program, we take a string value in str variable, where the content can be a float value. We convert this string value to a float value and print it to output.

Kotlin Program

fun main() {
    val str = "3.14"
    val num = str.toFloat()
    println(num)
}

Output

3.14

NumberFormatException if the string is not convertible to a float

If the given string is not convertible to a float value, then toFloat() function throws NumberFormatException as shown in the following program.

Kotlin Program

fun main() {
    val str = "3.14abc"
    val num = str.toFloat()
    println(num)
}

Output

Exception in thread "main" java.lang.NumberFormatException: For input string: "3.14abc"
	at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
	at java.base/jdk.internal.math.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
	at java.base/java.lang.Float.parseFloat(Float.java:455)
	at MainKt.main(main.kt:3)
	at MainKt.main(main.kt)