/commands/kotlin/string-to-int
kotlin convert string to int: toInt() vs toIntOrNull()
- tool
- Kotlin
- versions
- Kotlin 1.1+ (toIntOrNull), Kotlin 2.x
- os
- any
"42".toInt() converts a string to an Int and throws NumberFormatException when the string is not a valid number; "42".toIntOrNull() returns null instead of throwing. Prefer toIntOrNull() for user input and combine it with the Elvis operator for a default: val n = text.toIntOrNull() ?: 0. Both accept an optional radix, as in "ff".toInt(16).
Examples
fun main() {
println("42".toInt()) // 42
println("-17".toInt()) // -17
println("2147483647".toInt()) // Int.MAX_VALUE
println("abc".toIntOrNull()) // null
println(" 1000 ".toIntOrNull()) // null: whitespace is not allowed
println(" 1000 ".trim().toInt()) // 1000
println("2147483648".toIntOrNull()) // null: out of Int range
println("2147483648".toLong()) // fits in Long
val port = System.getenv("PORT")?.toIntOrNull() ?: 8080
println(port)
println("ff".toInt(16)) // 255
"1_000".toInt() // throws NumberFormatException
}The results in the comments follow the standard library documentation: the string may contain an optional leading + or - and digits only; anything else, including spaces, underscores and values outside Int.MIN_VALUE..Int.MAX_VALUE, makes toInt() throw and toIntOrNull() return null.
Conversion functions
| Function | Result | On invalid input |
|---|---|---|
| s.toInt() | Int | Throws NumberFormatException |
| s.toIntOrNull() | Int? | Returns null |
| s.toInt(radix) / s.toIntOrNull(radix) | Int / Int? | Same, for bases 2 to 36 |
| s.toLong() / s.toLongOrNull() | Long / Long? | For values beyond the Int range |
| s.toDouble() / s.toDoubleOrNull() | Double / Double? | For decimals such as 3.5 |
| s.toBigInteger() | BigInteger | Arbitrary size (JVM) |
| c.digitToInt() | Int | For a single Char digit; throws if it is not a digit |
Pitfalls
- Nullable results.
toIntOrNull()returnsInt?; passing it where anIntis expected fails with Type mismatch: inferred type is Int? but Int was expected. Supply a default with?:or check fornullfirst. - Nullable strings. On a
String?(for examplereadlnOrNull()or a map lookup), calls?.toIntOrNull(); a plains.toInt()is rejected with Only safe (?.) or non-null asserted (!!.) calls are allowed. - Decimals.
"3.5".toInt()throws; parse withtoDouble()and then usetoInt()on the number (which truncates) orroundToInt(). - Catching exceptions in loops is slower and noisier than
toIntOrNull(); reservetoInt()for input that must be valid, where an exception is the right outcome.
Confirm it worked
Test the edge cases your input can contain: an empty string, spaces, a minus sign and a value just above Int.MAX_VALUE. With toIntOrNull() each invalid one must give null, never an exception.
FAQ
Why does readln().toInt() fail on valid-looking input?
Surrounding spaces make the string invalid: " 1000 ".toInt() throws NumberFormatException. Call trim() first, or use toIntOrNull() and handle null.
How do I convert a Char digit to Int?
Use '7'.digitToInt() (Kotlin 1.5+). '7'.toInt() is deprecated and returned the character code (55), not the digit.
How do I parse a hexadecimal string?
Pass the radix: "ff".toInt(16) returns 255, and "ff".toIntOrNull(16) returns null instead of throwing for invalid input.