Kotlin example

How to convert a string to an int in Kotlin

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use text.toIntOrNull(). It returns an Int? that is null when the text isn't a whole number, so add a default with text.toIntOrNull() ?: 0. text.toInt() returns a plain Int and throws NumberFormatException instead. For numbers past 2147483647, use toLong() or toLongOrNull(); for hex, pass a radix: "ff".toInt(16). The other way round, n.toString() or "$n" turns an Int into text.

Kotlin puts the conversion on the string itself: every number type has a pair of extension functions, toInt() and toIntOrNull(), toLong() and toLongOrNull(), toDouble() and toDoubleOrNull(), and so on. The first of each pair throws on bad input, the second returns null. The sections below cover both, strings too big for an Int, whitespace, signs and other bases, text with a decimal point, the opposite direction from Int to String, and the Java habit Integer.parseInt, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1toIntOrNull() and toInt()Recommended

toIntOrNull() returns the number, or null when the whole string isn't a valid Int. Because the result is an Int?, the compiler makes you deal with the failure before you can do arithmetic: give a default with ?:, leave the function with ?: return, or check it with if. toInt() skips the null and throws NumberFormatException instead, which suits text you wrote yourself or input that has already been checked. Neither needs an import. For the null-handling operators, see how to check for null.

StringToInt.kt
// In a function, ?: return leaves early when the text does not parse
fun doubled(text: String): String {
    val n = text.toIntOrNull() ?: return "$text is not a whole number"
    return "$text doubled is ${n * 2}"
}

fun main() {
    // toInt() gives an Int, or throws when the text is not a number
    val n = "42".toInt()
    println("n + 1 = ${n + 1}")

    // toIntOrNull() gives Int?: null instead of an exception
    val count = "many".toIntOrNull() ?: 0
    println("count: $count")

    // What parses and what does not
    val inputs = listOf(
        "-17", "+5", "007", " 5", "3.0", "", "42abc", "3000000000",
    )
    for (input in inputs) {
        println("\"$input\" -> ${input.toIntOrNull()}")
    }

    // toInt() on the same bad input throws NumberFormatException
    try {
        println("42abc".toInt())
    } catch (e: NumberFormatException) {
        println("${e::class.simpleName}: ${e.message}")
    }

    println(doubled("21"))
    println(doubled("twenty"))
}

Output

"42" gives n + 1 = 43 and "many" falls back to count: 0. The loop shows how strict the parser is: a sign is fine (+5 gives 5) and leading zeros are ignored (007 gives 7), but a leading space, a decimal point, the empty string, trailing letters and a number bigger than an Int all give null. It never returns part of a number, so "42abc" is null, not 42. toInt() rejects the same strings with NumberFormatException: For input string: "42abc"; left uncaught, that exception ends the program.

2A String to a Long, and overflow

An Int holds up to 2147483647. IDs, timestamps in milliseconds and file sizes often go past that, and toIntOrNull() returns null for them. Parse those with toLong() or toLongOrNull(), which work exactly like the Int pair up to 9223372036854775807. The parsers always check the range; arithmetic does not, so a parsed Int that you add to can still wrap around. Every other integer type has the same pair, including the unsigned ones, and toBigInteger() takes any number of digits.

StringToLong.kt
fun main() {
    // Too big for an Int, fine for a Long
    val text = "9000000000"
    println(text.toIntOrNull())
    println(text.toLong())
    println(text.toLongOrNull() ?: 0L)

    // Long has a limit too: Long.MAX_VALUE
    println("9223372036854775807".toLongOrNull())
    println("9223372036854775808".toLongOrNull())

    // Int arithmetic does not check: it wraps around silently
    val max = "2147483647".toInt()
    println(max + 1)
    println(max.toLong() + 1)

    // Narrowing a Long to an Int keeps only the low 32 bits
    println("3000000000".toLong().toInt())

    // Every integer type has the same pair of functions
    println("127".toByte())
    println("200".toByteOrNull())
    println("4000000000".toUInt())
    println("-1".toUIntOrNull())

    // Bigger than a Long: BigInteger
    val big = "123456789012345678901234567890".toBigInteger()
    println(big * 2.toBigInteger())
}

Output

"9000000000" is null as an Int and 9000000000 as a Long. One past Long.MAX_VALUE gives null again. The overflow lines are the gotcha: max + 1 prints -2147483648 with no error, while widening first with toLong() gives the right 2147483648. Going the other way, "3000000000".toLong().toInt() doesn't fail either, it prints -1294967296, so parse straight to the type you need and let the parser reject what doesn't fit. "200".toByteOrNull() is null because a Byte stops at 127, and "-1".toUIntOrNull() is null because a UInt can't be negative.

3Whitespace, signs and other bases

Text from a file, a form or a command line often carries a space or a newline, and toInt() rejects both, so call trim() first. A single leading + or - is accepted; digit separators are not, neither 1_000 (that only works in source code) nor 1,000. For hex, binary or any base from 2 to 36, pass the radix: toInt(16), toIntOrNull(2). The text must not start with 0x; remove the prefix with removePrefix("0x"). To parse a list, mapNotNull converts each piece and drops the ones that fail.

TrimAndRadix.kt
fun main() {
    // toInt() does not skip spaces or newlines: trim first
    val line = "  42\n"
    println(line.toIntOrNull())
    println(line.trim().toIntOrNull())

    // One leading + or - is fine; separators are not
    println("+8".toInt() + "-3".toInt())
    println("1_000".toIntOrNull())
    println("1,000".toIntOrNull())
    println("1,000".replace(",", "").toInt())

    // Other bases: pass a radix from 2 to 36
    println("ff".toInt(16))
    println("FF".toIntOrNull(16))
    println("1010".toInt(2))
    println("777".toInt(8))

    // No 0x prefix: remove it first
    println("0x1F".toIntOrNull(16))
    println("0x1F".removePrefix("0x").toInt(16))

    // Parse a list and drop what does not parse
    val fields = "8,abc,15, 4".split(",")
    println(fields.mapNotNull { it.toIntOrNull() })
    println(fields.mapNotNull { it.trim().toIntOrNull() })
}

Output

" 42\n" is null until trim() removes the spaces and the newline. +8 plus -3 is 5, while 1_000 and 1,000 are both null; removing the comma gives 1000. Hex ff is 255 in either case, binary 1010 is 10 and octal 777 is 511. "0x1F" with radix 16 is null until the prefix is gone, then 31. In the list, the first mapNotNull quietly drops " 4" along with abc ([8, 15]); trimming each piece keeps it ([8, 15, 4]). A radix outside 2 to 36 throws IllegalArgumentException with radix 37 was not in valid range 2..36.

4Strings with a decimal point: Double and Float

"3.9".toInt() throws, because the text isn't a whole number. Parse it with toDouble() or toDoubleOrNull() (or the Float versions), then convert: toInt() on a Double drops the fraction, rounding toward zero, and roundToInt() from kotlin.math rounds to the nearest whole number. The Double parser is looser than the Int one: it accepts exponents, spaces around the number and a few spellings you may not want from a user.

DecimalStrings.kt
import kotlin.math.roundToInt

fun main() {
    // "3.9" is not an Int
    println("3.9".toIntOrNull())

    // Parse a Double, then convert it
    val price = "3.9".toDouble()
    println(price.toInt())
    println(price.roundToInt())
    println("-3.9".toDouble().toInt())
    println(2.5.roundToInt())
    println((-2.5).roundToInt())

    // What toDoubleOrNull() accepts
    val inputs = listOf(
        "3.14", ".5", "1e3", " 2.5 ", "3,5", "NaN", "Infinity", "1f", "abc",
    )
    for (input in inputs) {
        println("\"$input\" -> ${input.toDoubleOrNull()}")
    }

    // Float: the same functions with fewer digits
    println("3.14".toFloat())
    println("0.1".toFloat().toDouble())

    // A Double to an Int never throws: it clamps
    println(Double.NaN.toInt())
    println(1e20.toInt())
}

Output

3.9 becomes 3 with toInt() and 4 with roundToInt(), and -3.9 truncates to -3. Halves round up: 2.5 gives 3 but -2.5 gives -2. The loop shows the loose parser: " 2.5 " parses with its spaces, "NaN" and "Infinity" are numbers, and "1f", a Java float literal, is 1.0; only "3,5" and "abc" are null. Check isFinite() if you don't want the first two. A Float keeps about 7 digits, so 0.1f widened to a Double shows 0.10000000149011612. Converting a Double never throws, toInt() clamps: NaN becomes 0 and 1e20 becomes 2147483647, while roundToInt() on NaN throws Cannot round NaN value.

5An Int back to a String

This direction can't fail. n.toString() is the explicit conversion, and a string template, "$n" or "${n + 1}" for an expression, is what you use when the number sits inside other text. toString(radix) writes other bases, padStart adds leading zeros, and String.format adds grouping separators. Grouping follows the machine's locale by default, so pass one when the output must be the same everywhere. Watch nullable values: toString() on an Int? that is null returns the text "null".

IntToString.kt
import java.util.Locale

fun main() {
    val n = 42

    // toString() and string templates give the same text
    val a = n.toString()
    val b = "$n"
    println("$a $b ${a == b}")
    println("Total: ${n * 2} items")
    println(9000000000L.toString())

    // Other bases, and the sign stays a minus sign
    println(255.toString(16))
    println(255.toString(16).uppercase())
    println(5.toString(2))
    println((-255).toString(16))

    // Leading zeros and grouping
    println(7.toString().padStart(3, '0'))
    println("%05d".format(n))
    println(String.format(Locale.US, "%,d", 1234567))

    // A nullable Int: toString() turns null into "null"
    val missing: Int? = "abc".toIntOrNull()
    println(missing.toString())
    println(missing?.toString() ?: "none")

    // The round trip drops leading zeros
    println("0042".toInt().toString())
}

Output

toString() and "$n" both give 42 and compare equal (true). 255.toString(16) is ff, and 5 in binary is 101. A negative number keeps its sign, -ff, rather than the two's complement bits Java's Integer.toHexString prints. padStart(3, '0') and "%05d" give 007 and 00042, and Locale.US grouping gives 1,234,567. The nullable line prints null as text, which is easy to miss in a log or a UI; ?.toString() ?: "none" picks a real fallback. Parsing and printing again turns "0042" into 42.

6The Java habit: Integer.parseInt

Code converted from Java, and many older answers, use Integer.parseInt(text). It works in Kotlin, because java.lang is imported by default, and on the JVM toInt() calls it for you, so the result and the exception are the same. The catch is Long: in Kotlin that name means kotlin.Long, which has no parseLong, so Long.parseLong(text) fails to compile with Unresolved reference 'parseLong'. Write the Java class in full, or better, switch to toLong().

JavaParseInt.kt
fun main() {
    // java.lang is imported by default, so Integer works as in Java
    val a = Integer.parseInt("42")
    val b = Integer.valueOf("17")
    println(a + b)

    // Long means kotlin.Long here: name the Java class in full
    val big = java.lang.Long.parseLong("9000000000")
    println(big)

    // Same parser, same exception as toInt()
    try {
        Integer.parseInt("12abc")
    } catch (e: NumberFormatException) {
        println(e.message)
    }

    // The Kotlin way reads better and has a null-returning twin
    println("42".toInt() + "17".toInt())
    println("9000000000".toLong())
    println("12abc".toIntOrNull() ?: -1)
}

Output

Both halves print 59 and 9000000000, and a bad string gives the same For input string: "12abc" message either way. There is no reason to keep Integer.parseInt in Kotlin code: toInt() reads left to right, works on a nullable string with ?., and has toIntOrNull(), which Java has no equivalent of. The same goes for Double.parseDouble, which becomes toDouble().

7Which should you use?

MethodGivesOn bad inputBest for
text.toIntOrNull()Int?nullInput from users, files, the network
text.toInt()IntThrows NumberFormatExceptionText you know is a number
text.toLongOrNull()Long?nullIDs, timestamps, values past 2147483647
text.toIntOrNull(16)Int?nullHex, binary and other bases
text.toDoubleOrNull()Double?null, but accepts NaN and " 2.5 "Decimals; then toInt() or roundToInt()
n.toString(), "$n"StringCannot failInt back to String
Integer.parseInt(text)IntThrows NumberFormatExceptionAvoid: toInt() does the same

Frequently asked questions

What is the difference between toInt() and toIntOrNull()?

They accept exactly the same strings. On bad input, toInt() throws NumberFormatException with a message like For input string: "42abc", while toIntOrNull() returns null. Use toIntOrNull() with ?: for anything a user typed, and toInt() when a failure would be a bug.

How do I convert a String to a Long in Kotlin?

Call text.toLong(), or text.toLongOrNull() to get null instead of an exception. "9000000000".toLong() gives 9000000000, which is too big for an Int. A Long goes up to 9223372036854775807; for longer numbers use toBigInteger(). The Java form Long.parseLong(text) does not compile in Kotlin; java.lang.Long.parseLong(text) does.

How do I convert a String like "3.9" to an Int?

Parse it as a Double first: "3.9".toDouble().toInt() gives 3, because toInt() drops the fraction. For the nearest whole number, use roundToInt() from kotlin.math: "3.9".toDouble().roundToInt() gives 4. "3.9".toInt() itself throws NumberFormatException.

How do I convert a nullable String to an Int?

Use the safe call: text?.toIntOrNull() is null both when text is null and when it is not a number, so text?.toIntOrNull() ?: 0 covers both with one default. Calling toInt() on a String? without ?. does not compile.

How do I detect overflow when doing math with parsed Ints?

The parsers reject values that do not fit, but +, - and * on Int wrap around silently: "2147483647".toInt() + 1 is -2147483648. Widen to Long first (n.toLong() + 1), or use Math.addExact and Math.multiplyExact, which throw ArithmeticException with the message "integer overflow".

How do I convert a Char to an Int in Kotlin?

For the digit value, use digitToInt(): '7'.digitToInt() is 7, 'f'.digitToInt(16) is 15, and digitToIntOrNull() returns null for a non-digit. '7'.code gives the character code, 55. The old '7'.toInt() also returns 55, not 7, and is deprecated in favor of code.

Does toInt() accept digits from other alphabets?

Yes. On the JVM both toInt() and toIntOrNull() accept decimal digits from other scripts, so the Arabic-Indic digit "٣" parses to 3. If a field must contain ASCII digits only, check it first, for example with text.all { it in '0'..'9' }, before converting.

Run it yourself

Open any of these in the full Kotlin editor to tweak, run and share.

Kotlin playground