kotlin

Print 0001 to 1000 in Kotlin. How to add padding to numbers?


I want to print 0001 (note the 3 preceding 0s), and incremental 1 at a time, and reach 1000 to stop. How could I do that in Kotlin without complex appending the 0s myself?

The below is not helping as it will not have preceding 0s.

for (i in 1..1000) print(i)

Solution

  • You can use padStart:

    (0..1000)
        .map { it.toString().padStart(4, '0') }
        .forEach { println(it) } // forEach(::println) function reference also works here
    

    It’s part of the Kotlin Standard Library and available for all platforms.