Pad an integer with leading zeros in Kotlin
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.
1 2 3 4 5 6 |
fun main() { val intValue = 111 val n = 5 println(intValue.toString().padStart(n, '0')) // "00111" } |
To right pad a string to the specified length with space or the specified character, use the library function padEnd()
.
1 2 3 4 5 6 |
fun main() { val intValue = 111 val n = 5 println(intValue.toString().padEnd(n, '0')) // "11100" } |
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.
1 2 3 4 5 6 7 |
fun main() { val intValue = 111 val s = "%05d".format(intValue) println(s) // 00111 } |
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:
1 2 3 4 5 6 7 |
fun main() { val intValue = 111 val s = String.format("%05d", intValue) println(s) // 00111 } |
That’s all about padding an integer with leading zeros in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)