How to prepend numbers with 0 if less than 10 in chat?

I am creating a timer system using the scoreboard.

I would like the timer to display on the actionbar title in the format HH:MM:SS.

Currently I already have command algorithms that will set the number of hours, minutes, and seconds from the total number of seconds.

This is the command I use to output the time:

/tellraw @a [{"score":{"name":"hrs","objective":"time"}}, {"text":":"}, {"score":{"name":"mins","objective":"time"}}, {"text":":"}, {"score":{"name":"secs","objective":"time"}}]

Although this command may look long, it is simply concatenating each value and separating them with colons.

But however, when the hours, mins, or seconds are less than 10, they are displayed like this: 0:4:13.

I would like to prepend every value less than 10 with a 0, so that it displays like this: 00:04:13.

The only way I can think of doing this is to test specifically for each case of which values are less than 10, and prepend those with a 0 before output.

But this will get repetitive as there are many different combinations, and I think I will have to include one test for each combination of which values are less than 10.

I think there may be an easier way that I am missing out on. What is it, if any?


Your idea is already close to the best you can do.
Maybe it helps to store partial strings like "01:" elsewhere first and then concatenate those, that way you don't get exponentially more combinations to check for when you get more elements. But for your 3 elements and 8 combinations, it might not be worth it.


I have found a solution myself. This solution uses a sign to combine all three parts separately:

For each part (hours, minutes, and seconds) we set a separate line of a sign to the value, and prepend a 0 to the front if necessary:

execute if score #hrs time matches ..9 run data modify block <sign> Text1 set value '["0",{"score":{"name":"#hrs","objective":"time"}}]'
execute if score #hrs time matches 10.. run data modify block <sign> Text1 set value '{"score":{"name":"#hrs","objective":"time"}}'

execute if score #mins time matches ..9 run data modify block <sign> Text2 set value '["0",{"score":{"name":"#mins","objective":"time"}}]'
execute if score #mins time matches 10.. run data modify block <sign> Text2 set value '{"score":{"name":"#mins","objective":"time"}}'

execute if score #secs time matches ..9 run data modify block <sign> Text3 set value '["0",{"score":{"name":"#secs","objective":"time"}}]'
execute if score #mins time matches 10.. run data modify block <sign> Text3 set value '{"score":{"name":"#secs","objective":"time"}}'

Then we just /tellraw all three parts at once, thanks to the nbt component.

tellraw @a [{"block":"<sign>","nbt":"Text1","interpret":true}, ":",{"block":"<sign>","nbt":"Text2","interpret":true}, ":",{"block":"<sign>","nbt":"Text3","interpret":true}]