Cyrus
Cyrus

Reputation: 9425

Format a number to string, fill 0 when it's not enough two characters

I want to format the number to String and fill 0 when it's not enough two characters

fun formatDuration(val duration):String {
    val minutes = duration.toInt() / 60
    return  "$minutes"
}

For example, if minutes is 6, it should displayed 06 rather than 6.

Upvotes: 9

Views: 3559

Answers (2)

N. D.
N. D.

Reputation: 321

You can achive this with padStart

Example:

val padWithSpace = "125".padStart(5)
println("'$padWithSpace'") // '  125'

val padWithChar = "a".padStart(5, '.')
println("'$padWithChar'") // '....a'

// string is returned as is, when its length is greater than the specified
val noPadding = "abcde".padStart(3)
println("'$noPadding'") // 'abcde'

Upvotes: 9

deHaar
deHaar

Reputation: 18588

You can padStart the toString() result of minutes.

I tried your code in the Kotlin Playground and it wasn't compilable / runnable. For the following example, I had to change parts of your fun:

fun main() {
    println(formatDuration(364.34))
}

fun formatDuration(duration: Double): String {
    val minutes = duration.toInt() / 60
    // fill the result to be of 2 characters, use 0 as padding char
    return minutes.toString().padStart(2, '0')
}

Executing this results in the output 06.

Alternatively, you can simply use String.format() from Java, just

return "%02d".format(minutes)

instead of return minutes.toString().padStart(2, '0'), the result stays the same.

Upvotes: 16

Related Questions