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)
The standard solution to pad an integer with leading zeroes in Kotlin is using the library function padStart() . It left-pads a string to the specified length with space by default or the specified character. Note to call padStart() , first convert the given Int value to a String.
format("%05d", yournumber); for zero-padding with a length of 5.
The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With