Add leading zeros to a number in Kotlin

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

String.format()

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"

CharSequence.padStart()

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 *