Add Leading Zeros to a Number in Kotlin

Working with numbers in Kotlin can be tricky, especially when you need to add leading zeros to a number. Fortunately, Kotlin provides several different methods for adding leading zeros to a number, making it easy to format numbers in the way you need. In this blog, we will introduce 2 ways to add zeroes to a number in Kotlin.

String.format()

Adding leading zeros to a number in Kotlin is relatively straightforward. All you need to do is use the String.format() function. This function takes two arguments: a format string and an argument list. The format string is used to specify the desired output format and the argument list contains the values to be formatted.

To add leading zeros to a number, the format string should contain a %0n specifier where n is the desired length of the output string. For example, to add leading zeros to a number to make it five digits long, the format string would be %05d. The d in the format string specifies that an argument is a decimal number.

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

CharSequence.padStart()

Another way to add leading zeros to a number in Kotlin is to use the String.padStart() function. This method returns a char sequence with the content of this char sequence padded at the beginning to the specified length with the specified character or space.

The String.padStart() function takes two arguments: a length and a character. The length argument specifies the desired length of the output string and the character argument specifies the character to use for padding.

For example, to add leading zeros to the number 123, the length argument would be 5 and the character argument would be 0. The output of the String.padStart() function would be 00123.

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

Leave a Comment

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


Scroll to Top

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.

Close