1. Introduction

As developers, it’s common to encounter situations where we need to convert a string to a float.

In this tutorial, we’ll discuss various methods to convert a String to a Float in Kotlin.

2. Using the toFloat() Method

One of the easiest ways to convert a string to a float in Kotlin is by using the toFloat() method. This method is available in the standard Kotlin library and can be called on any String:

@Test
fun `convert string to float using the toFloat method`() {
    val myString = "8.73"

    assertEquals(8.73F, myString.toFloat())
}

In this first test, we declare a string and assign it to “8.73”. Subsequently, we call the toFloat() method on the string to get the float representation of the string. However, this will throw an exception when we call this method on a string that is not a valid representation of a float.

So to safely handle these string representations, we can use the toFloatOrNull() method instead, as seen below. This method returns null when we use it on a string that is not a valid float:

@Test
fun `convert string to float using the toFloatOrNull method`() {
    val myString = "Invalid"

    assertNull(myString.toFloatOrNull())
}

3. Using the NumberFormat Class

Another interesting way to achieve our goal is by using the NumberFormat class. Similarly, it is readily available in Kotlin’s standard library.

This class provides us with methods to conveniently format and parse numbers:

fun stringToFloat(input: String): Float {
    val nf = NumberFormat.getInstance(Locale.US)
    return nf.parse(input).toFloat()
}

Now, let’s test this method for correctness:

@Test
fun `convert string to float using the NumberFormat class`() {
    assertEquals(8.73F, stringToFloat("8.73"))
}

This approach is different from the previous approach in that it allows us to specify a Locale for our NumberFormat instance. We use the US locale, which ensures that the decimal separator is a dot (.) rather than a comma (,) which is used in some locales.

Once we have our NumberFormat instance, we can parse() our string with it and then call the toFloat() method to convert the generic parsed Number to a Float.

Note that parsing an invalid string representation of a Float will lead to a ParseException. So, to handle this kind of situation efficiently, we can execute the parsing in a try-catch block.

4. Using Regex

We can also use regular expressions to extract a float value from a given string:

fun stringToFloatUsingRegex(input: String): Float {
    val regex = Regex("[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)")
    val match = regex.find(input)
    
    return match?.value?.toFloatOrNull()? : 0f
}

This method is more powerful than the previous methods, as it can extract decimal and float values from a more complex string. That is, given a string containing any floating point or decimal number, this approach will extract the float string from it and then convert it to an actual float number.

To be sure our method works as expected, let’s test it as well:

@Test
fun `convert string to float using Regex`() {
    assertEquals(8.73F, stringToFloatUsingRegex("8.73"))
    assertEquals(8.73F, stringToFloatUsingRegex("this is a float number 8.73"))
}

Furthermore, we can use this same regex to validate that a string is a floating point only, instead of extracting a floating point number from the string. All we need to do is surround this regex with the ^ and $ symbols to denote that we expect this pattern to match the whole word.

5. Conclusion

In this article, we’ve explored various ways to convert a String to a Float in Kotlin. First, we used methods and classes readily available in Kotlin’s library, such as the toFloat() method and the NumberFormat class. Next, we looked at another interesting technique using regex. Each of these methods comes with advantages and disadvantages, and the choice of method depends on the specific use case.

As always, the code samples and relevant test cases for this article can be found over on GitHub.

Comments are closed on this article!