This article explores different ways to decode a String to a Float or Int in Kotlin.

1. Using toDouble() function

A simple solution to parse a string to get the corresponding double is using the toDouble() function. A typical invocation for this method would look like:

Download Code

 
The toDouble() function throws NumberFormatException if the string is not a valid representation of a number. The following code example uses the toDoubleOrNull() function, which parses the string as a Double and returns the result or null if the string is not a valid representation of a number.

Download Code

 
Alternatively, we can enclose the toDouble() function within a try-catch block.

Download Code

 
To get the corresponding integer value, we can cast the resultant double value using the toInt() function.

Download Code

2. Using toFloat() function

Alternatively, we can use the toFloat() function to parse a string to a float. Or use the toFloatOrNull() function for null-safe version.

Download Code

 
To get the corresponding integer value, cast the resultant float value as discussed before.

Download Code

3. Using toInt() function

To parse the string as a signed decimal integer, we can use the toInt() function. To avoid an exception, we can invoke the toInt() function within a try-catch block, as shown below:

Download Code

 
A better solution is to use the toIntOrNull() function, which parses the string as an Int number and returns the result or null if the string is not a valid representation of a number.

Download Code

That’s all about decoding a String to a Float or Int in Kotlin.