Number Parsing in Kotlin

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Kotlin.

import kotlin.NumberFormatException

fun main() {
    // With toDouble(), we parse the string to a Double
    val f = "1.234".toDouble()
    println(f)

    // For parsing integers, we can use toInt() or toLong()
    val i = "123".toLong()
    println(i)

    // Kotlin can recognize hex-formatted numbers with the "0x" prefix
    val d = "0x1c8".toLong(16)
    println(d)

    // For unsigned integers, we can use toULong()
    val u = "789".toULong()
    println(u)

    // toInt() is a convenient function for basic base-10 int parsing
    val k = "135".toInt()
    println(k)

    // Parse functions throw NumberFormatException on bad input
    try {
        "wat".toInt()
    } catch (e: NumberFormatException) {
        println(e.message)
    }
}

In Kotlin, number parsing is done using extension functions on the String class. These functions are part of the Kotlin standard library, so no additional imports are needed for basic parsing.

With toDouble(), we parse the string to a Double. This is equivalent to ParseFloat in the original example.

For parsing integers, we can use toInt() for 32-bit integers or toLong() for 64-bit integers. The base is inferred from the string by default, but can be specified as a parameter.

Kotlin can recognize hex-formatted numbers with the “0x” prefix. We use toLong(16) to parse a hexadecimal string.

For unsigned integers, we can use toULong().

toInt() is a convenient function for basic base-10 int parsing, similar to Atoi in the original example.

Parse functions in Kotlin throw NumberFormatException on bad input, which we can catch to handle parsing errors.

To run the program:

$ kotlinc number-parsing.kt -include-runtime -d number-parsing.jar
$ java -jar number-parsing.jar
1.234
123
456
789
135
For input string: "wat"

Next, we’ll look at another common parsing task: URLs.