toInt()
You can call toInt() on a String to turn it into an Integer.
val number_int = str.toInt()
If it cannot be converted, it will throw a NumberFormatException error.
You could put it in a try-catch block:
try { val strVal = "IamNotanInteger" val intVal = strVal.toInt() println(intVal) } catch (e: NumberFormatException) { println("This String is not convertible.") }
toIntOrNull()
toIntOrNull() will also convert a String into an Integer, but it will return null instead of throwing an error.
fun main() { val strVal = "246b" val intVal = strVal.toIntOrNull() println(intVal) // null }
Integer.parseInt()
Here’s how to use the parseInt() method to convert Kotlin String to Int.
fun main() { val strVal = "246" val intVal = Integer.parseInt(strVal) println(intVal) // 246 }
Non-Decimal System
You can pass a radix into the toInt() and toIntOrNull() methods:
fun main() { val base16String = "3F" val base16Int = base16String.toInt(16) // String Interpolation println("$base16Int") // 63 (If I did the maths correct...) }
Useful Links
String.toInt(), wrap it intry-catchand handle theNumberFormatException.String.toInt()available.toInt()on yourStringinstances. For exampleargs[0].toInt().toIntOrNullto get aInt?result, that way you don't have to use try-catch.