0

I am trying to split a big number into individual digits. This is how I'm doing it:

fun main() {
    var number = 8675309;
    val string = number.toString()
    println(string)
    val numbers = string.map {
        println(it)
        it.toInt()
    }
    numbers.forEach { println(it) }
}

Here's a link to a Kotlin playground that has this code.

To do this, I first convert the number to a string using toString(). Then I print this string to verify that it's the same number as a string.

I then map over this string, print each individual character to verify that it's the correct character, and then convert the character to an integer with toInt().

I think use forEach() to go over the newly created array of numbers and print each of these numbers, but the resulting numbers are not related to to the original number variable.

Why does this not work?

rpivovar
  • 3,150
  • 13
  • 41
  • 79

1 Answers1

2

Inside string.map you are iterating over Char values, not String values. When you call toInt() on a Char you get the ASCII code for that character, which is what you see being printed at the end of your program.

An easy way to fix this is to convert the Char values into String values first, before calling toInt() so the result will be what you expect:

fun main() {
    var number = 789456123;
    val string = number.toString()
    println(string)
    val numbers = string.map {
        println(it)
        it.toString().toInt()
    }
    numbers.forEach { println(it) }
}
Mark B
  • 183,023
  • 24
  • 297
  • 295