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

Kotlin

Kotlin Problem Overview


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)

Kotlin Solutions


Solution 1 - Kotlin

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.

Solution 2 - Kotlin

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.

Solution 3 - Kotlin

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)) }

Solution 4 - Kotlin

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

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

Solution 5 - Kotlin

With PadStart and without any map or multiple loops,

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

Solution 6 - Kotlin

Using a string template will call toString() under the hood and make the call even shorter:

(0..1000).forEach { println("$it".padStart(4, '0')) }

Mapping it first, is unecessary effort.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElyeView Question on Stackoverflow
Solution 1 - Kotlins1m0nw1View Answer on Stackoverflow
Solution 2 - KotlinMarko TopolnikView Answer on Stackoverflow
Solution 3 - KotlinIvan SamborskiiView Answer on Stackoverflow
Solution 4 - KotlinvoddanView Answer on Stackoverflow
Solution 5 - KotlinJTeamView Answer on Stackoverflow
Solution 6 - KotlinWilli MentzelView Answer on Stackoverflow