Skip to content

/commands/kotlin/string-to-int

kotlin convert string to int: toInt() vs toIntOrNull()

The commands on this page have not been executed by our verification runner yet.updated
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

Parse.kt
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

FunctionResultOn invalid input
s.toInt()IntThrows 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()BigIntegerArbitrary size (JVM)
c.digitToInt()IntFor a single Char digit; throws if it is not a digit

Pitfalls

  • Nullable results. toIntOrNull() returns Int?; passing it where an Int is expected fails with Type mismatch: inferred type is Int? but Int was expected. Supply a default with ?: or check for null first.
  • Nullable strings. On a String? (for example readlnOrNull() or a map lookup), call s?.toIntOrNull(); a plain s.toInt() is rejected with Only safe (?.) or non-null asserted (!!.) calls are allowed.
  • Decimals. "3.5".toInt() throws; parse with toDouble() and then use toInt() on the number (which truncates) or roundToInt().
  • Catching exceptions in loops is slower and noisier than toIntOrNull(); reserve toInt() 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.

Sources