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

You can use padStart:

(0..1000)
    .map { it.toString().padStart(4, '0') }
    .forEach(::println)

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


If you are satisfied with a JVM-specific approach, you can do what you'd to in Java:

(1..1000).forEach { println("%04d".format(it)) }

String.format is an extension function defined in StringsJVM and it delegates straight to the underlying String.format, so it's not in the universal standard library.


In Kotlin you can use String.format() (the same as in Java):

"%04d".format(i)

In your case, you can write down it in the following way:

(1..1000).forEach { println("%04d".format(it)) }

Just to be clear, for-loops are fine too:

for(i in 1..1000)
    println("%04d".format(i))