Convert string to int in Kotlin
To convert a given string value to an integer value in Kotlin, you can use String.toInt()
function.
Call toInt()
function on the string value str
.
str.toInt()
The function returns an integer value created from the content in String value.
Examples
Convert the string “6523” to integer
In the following program, we take a string value in str
variable, where the content can be an integer. We convert this string value to an integer value.
Kotlin Program
fun main() {
val str = "6523"
val num = str.toInt()
println(num)
}
Output
6523
NumberFormatException if the string is not convertible to an int
If the given string is not convertible to an integer value, then toInt()
function throws NumberFormatException
as shown in the following program.
Kotlin Program
fun main() {
val str = "6523 apples"
val num = str.toInt()
println(num)
}
Output
Exception in thread "main" java.lang.NumberFormatException: For input string: "6523 apples"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at MainKt.main(main.kt:3)
at MainKt.main(main.kt)