Add Leading Zeros to a Number in Kotlin

When you need to format a number for display, you may want to add leading zeroes to make it appear more uniform.

In many cases, date and time need a leading zero before the actual value.

In Kotlin, you can use the format function to add leading zeroes to a number. For example, the following code will add leading zeroes to the number 123 so that it appears as 000123:

val num = 123 
val formattedNum = String.format("%06d", num) 
println(formattedNum) // 000123

Alternatively, you can use the String.padStart function to achieve the same result:

val num = 123 
val formattedNum = num.toString().padStart(6, "0")
println(formattedNum) // 000123

val month = "7"..padStart(2, "0") 
println(month ) // 07

We need to add leading zeroes to a number because it makes it easier to read and understand. When there are no leading zeroes, it can be difficult to determine which number is which, especially if there are multiple numbers with similar digits. For example, the number “8” looks very similar to the number “80”, but if we add a leading zero to the number “8”, it becomes clear that it is the smaller number.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.