Android Studio Kotlin - How to display 2 digit number in text?

Viewed 2926

On creating a timer In Android Studio Kotlin.

I'd like to display the time value as it's 2 digit number like '01:04:07'.

Please see the below.

enter image description here

enter image description here

At this point, how do I change the code?

3 Answers

Simply use String.format() like:

timerDisplay.text = String.format("%02d:%02d:%02d", lapsHours, lapsMinutes, lapsSeconds)

You can use DecimalFormat as below:

  val f: NumberFormat = DecimalFormat("00")
  timerDisplay.text = "${f.format(lapshours)}:${f.format(lapsMin)}:${f.format(lapsSec)}"
   

You can use your extension function on Int like

fun Int.format(): String{
    return if(this<10 && this>=0) "0"+this.toString() else this.toString()
}

simple call format() function on your Int variable to get your required format.

timerDisplay.text = "${lapsHours.format()} : ${lapsMinutes.format()} : ${lapsSeconds.format()}"
Related