This article explores different ways to pad an integer with leading zeros in Kotlin.

1. Using padStart() function

The standard solution to pad an integer with leading zeros 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.

Download Code

 
To right pad a string to the specified length with space or the specified character, use the library function padEnd().

Download Code

2. Using format() function

Another approach to pad an integer with leading zeros is using the format() function. It can be called on a format string with the '0' flag, causing the output to be padded with leading zeros until the string reaches the specified width.

The typical implementation of this approach would look like below.

Download Code

 
Note that format() is an extension function defined in StringsJVM and it delegates to the java.lang.String.format() function. Therefore, the above code is equivalent to:

Download Code

That’s all about padding an integer with leading zeros in Kotlin.