
Happy learning! See you again.This article will cover a guide on converting code written in the Kotlin programming language to Java programming language and vice versa. Today we’ve known way to convert a String to some types such as: Int, Long, Float, Double in Kotlin/Android.

One of the most common tasks in any programming language is to convert a String to a Number type. Val double2: Double? = dstr2.toDoubleOrNull() Exception in thread "main" : For input string: "A1.23" toDoubleOrNull() to convert the string to a Double, return a null if the string is not a valid representation of a Double.toDouble() to parse the string to a Double, NumberFormatException is thrown if the string is not a valid representation of a Double.Val float2: Float? = fstr2.toFloatOrNull() Exception in thread "main" : For input string: "A123.456" toFloatOrNull() to convert the string to a Float, return a null if the string is not a valid representation of a Float.toFloat() to parse the string to a Float, NumberFormatException is thrown if the string is not a valid representation of a Float.Exception in thread "main" : For input string: "42.42" To change to another valid radix, you can pass a parameter to these methods. toLongOrNull() to convert the string to a Long, return a null if the string is not a valid representation of a Long.toLong() to parse the string to a Long, NumberFormatException is thrown if the string is not a valid representation of a Long.Exception in thread "main" : For input string: "1234" Exception in thread "main" : For input string: "42.1" You can use any valid radix by passing a parameter to the methods above.

toIntOrNull() to convert the string to an Int, return a null if the string is not a valid representation of an Integer.īy default, the radix is 10.toInt() to parse the string to an Int, NumberFormatException is thrown if the string is not a valid representation of an Integer.In this tutorial, I will show you how to convert String to Int, Long, Float, Double in Kotlin/Android.
