Kotlin: convert string containing only numbers to Int

Kotlin fun
Kotlin fun

Converting Characters of a string containing only numbers to Int was a Kotlin task I recently faced.

Coding a for loop to iterate over the characters of a string was quickly done.
I browsed quickly through text funs and thought toInt can do the trick.

Well, not really 😉

Reading the toInt documentation also did not help in the first place unfortunately: Parses the string as an Int number and returns the result.

Reading about ascii printable characters did help me to solve the task:

The fun toInt returns different results if performed on top of a string or a character:

$ kotlinc
>>> "2".toInt()
>>> '2'.toInt()

My case was about Characters. One solution is to subtract 48 in order to retrieve the expected 2 as Int for the Character ‘2’ .

The gist below contains several approaches to achieve this. The String someText contains not only numbers for testing purposes.

fun main(args: Array) {
    val someText = "ABC1234567890"
    for (i in (0 .. (someText.length-1))){
        println(" number[$i]: ${someText[i]}")
        println("(number[$i] is Char): ${(someText[i] is Char)}")
        /* toInt return ascii dev code of a Character,
        _not_ the Character as Int in case of numbers */
        println(" number[$i].toInt(): ${someText[i].toInt()}")
        println(" number[$i].toString().toIntOrNull(): " +
        /* ascii to Int : 48 is ascii code for '0' */
        println(" number[$i].toInt() - 48: ${someText[i].toInt() - 48}")
        /* subtracts character zero ('0') thats ascii dec code is 48 */
        println(" number[$i] - '0': ${someText[i] - '0'}")


When converting Text to Int in Kotlin be aware of:

Be the first to comment

Leave a Reply

Your email address will not be published.


This site uses Akismet to reduce spam. Learn how your comment data is processed.