Pages

Thursday, January 7, 2021

How To Convert String to Float in Kotlin?

1. Overview

In this tutorial, We will learn how to convert the String value to Float in Kotlin. This conversion is done using toFloat() method of String class.

But there are many cases where it gives parsing errors for wrong inputs.

How To Convert String to Float in Kotlin?


2. Kotlin String to Float using toFloat() Method

Converting string to float is done with toFloat() method of string class.

toFloat() method is to parse the String value into Float. If the string is not a valid form of a number or any non-number presents then it throws NumberFormatException.


package com.javaprogramto.kotlin.conversions

fun main(args: Array<String<) {

    var str : String = "12345.678"
    var float1 : Float = str.toFloat();
    println("string to float - float1 $float1")

    var str2 : String = "A123"
    var float2 : Float = str2.toFloat();
    println("string to float - float2 $float2")
    
}


Output:


string to float - float1 12345.678
Exception in thread "main" java.lang.NumberFormatException: For input string: "A123"
	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:461)
	at com.javaprogramto.kotlin.conversions.StringToFloatExampleKt.main(StringToFloatExample.kt:10)


3. Kotlin String to Float using toFloatOrNull() Method

Next, use the another method for string to float conversion if the input string is not a valid number.

Call toFloatOrNull() method to get the null value if the string is having at least one non-digit.

Method toFloatOrNull() will convert String to Float.


package com.javaprogramto.kotlin.conversions

fun main(args: Array<String>) {

    var str : String = "456.75F"
    var float3 = str.toFloatOrNull();
    println("string to float - float3 $float3")

    var str2 : String = "PI3.14"
    var float4 = str2.toFloatOrNull();
    println("string to float - float4 $float4")
}


Output:

string to float - float3 456.75
string to float - float4 null


Note: When you are calling the toFloatOrNull() method, you should not specify the type to hold the value like var float3 : Float = str.toFloatOrNull(). This will give the compile error "Kotlin: Type mismatch: inferred type is Float? but Float was expected"


4. Conclusion

In this article, We've seen how to convert the string values into Float in Kotlin. And also how to handle if the string is containing the characters other than numbers.

GitHub

Kotlin Ternary Operator


No comments:

Post a Comment

Please do not add any spam links in the comments section.