Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

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) 
like image 467
Elye Avatar asked Jun 29 '18 08:06

Elye


People also ask

How to add 0 in front of number in Kotlin?

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.

How can I pad an integer with zeros on the left?

format("%05d", yournumber); for zero-padding with a length of 5.

How do you add leading zeros to a String in Java?

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.


2 Answers

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.

like image 119
s1m0nw1 Avatar answered Sep 28 '22 10:09

s1m0nw1


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.

like image 32
Marko Topolnik Avatar answered Sep 28 '22 10:09

Marko Topolnik