Convert a string to an integer in Kotlin
This article explores different ways to convert a string to an integer in Kotlin. If the value of the specified string is negative, the sign should be preserved in the resultant integer.
1. Using toInt() function
You can easily convert the given string to an integer with the toInt() function. It throws a NumberFormatException if the string does not contain a valid integer.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun toInteger(s: String) { try { val value = s.toInt() println("The value is $value") } catch (ex: NumberFormatException) { println("The given string is non-numeric") } } fun main() { val s = "1024" toInteger(s) } |
Output:
The value is 1024
Note that this function fails when the numeric value falls outside the valid integer data type range. If you need to work with the larger values, consider using the toLong() function.
|
1 2 3 4 5 6 7 8 |
fun toLong(s: String) { try { val value = s.toLong() println("The value is $value") } catch (ex: NumberFormatException) { println("The given string is non-numeric") } } |
2. Using toIntOrNull() function
Alternatively, you can use the toIntOrNull() function, which parses the string as an Int number and returns the result or null if the string is not a valid representation of a number.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun toInteger(s: String) { val value = s.toIntOrNull() if (value != null) { println("The value is $value") } else { println("The given string is non-numeric") } } fun main() { val s = "1024" toInteger(s) } |
Output:
The value is 1024
You can also combine toIntOrNull() with the safe call operator and a scope function.
|
1 2 3 4 5 6 7 8 9 10 |
fun toInteger(s: String) { s.toIntOrNull()?.let { println("The value is $it") } } fun main() { val s = "1024" toInteger(s) } |
Output:
The value is 1024
As with the toInt() function, this fails when the numeric value falls outside the integer range. If you need to work with the larger values, consider using the toLongOrNull() function.
|
1 2 3 4 5 |
fun toLong(s: String) { s.toLongOrNull()?.let { println("The value is $it") } } |
3. Using valueOf() function
The Integer class has valueOf() function that returns the integer value specified by the string.
|
1 2 3 4 5 6 7 |
fun main() { val s = "1024" val value = Integer.valueOf(s) println(value) // 1024 } |
That’s all about converting a string to an integer in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)