Add leading zeros to a number in Kotlin

There are 2 ways to add zeroes to a number in Kotlin.


This method returns a string obtained by substituting the specified arguments, using the default locale.

val monthOfYear = 2
val numberWithLeadingZero = String.format("%02d", monthOfYear)
println(numberWithLeadingZero) // "02"


This method returns a char sequence with content of this char sequence padded at the beginning to the specified length with the specified character or space.

val padWithZeros = "5".padStart(2, '0')
println(padWithZeros) // "05"

Leave a Comment

Your email address will not be published. Required fields are marked *

We care about your privacy and data security. Google serves cookies to analyse traffic and show ads on this site. By using this site you agree to these cookies being set. 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.