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.
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:
Next, we’ll look at another common parsing task: URLs.