How to convert a string to a float or double in Kotlin
How to convert a string to a float or double in Kotlin.
Here is a step-by-step tutorial on how to convert a string to a float or double in Kotlin.
Converting a String to a Float
To convert a string to a float in Kotlin, you can use the toFloat() function. Here's how you can do it:
- Declare a string variable that contains the string you want to convert to a float.
val str = "3.14"
- Use the
toFloat()function to convert the string to a float.
val floatValue = str.toFloat()
- The
toFloat()function returns the float value of the string. You can now use thefloatValuevariable as a float in your code.
Here's a complete example:
val str = "3.14"
val floatValue = str.toFloat()
// Using the floatValue variable
println(floatValue) // Output: 3.14
Converting a String to a Double
To convert a string to a double in Kotlin, you can use the toDouble() function. Here's how you can do it:
- Declare a string variable that contains the string you want to convert to a double.
val str = "3.14"
- Use the
toDouble()function to convert the string to a double.
val doubleValue = str.toDouble()
- The
toDouble()function returns the double value of the string. You can now use thedoubleValuevariable as a double in your code.
Here's a complete example:
val str = "3.14"
val doubleValue = str.toDouble()
// Using the doubleValue variable
println(doubleValue) // Output: 3.14
Handling Number Format Exceptions
When converting a string to a float or double, it's important to handle potential Number Format Exceptions that may occur if the string cannot be parsed as a valid number.
To handle such exceptions, you can use a try-catch block. Here's an example:
val str = "abc" // Invalid number string
try {
val floatValue = str.toFloat()
println(floatValue)
} catch (e: NumberFormatException) {
println("Invalid number format")
}
In this example, if the string "abc" cannot be converted to a float, a NumberFormatException will be thrown. The catch block will then handle the exception and print an error message.
That's it! You now know how to convert a string to a float or double in Kotlin.