String formatting: picking the right most 2 chars

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By DaveMS

In a racing game I want to display a timer on top of the screen.

In a variable called time I store the elapsed time since the start of the game:

func _process(delta):
    time =+ delta
    ...

I want to represente the time as MM:SS.dd, where MM are the elapsed minutes, SS are the seconds and dd are the tenths of seconds.

Since I need to show the zeros on the left when the numbers are between 0 and 9, after calculating the single portions of the time, I use the following to format the string:

LabelNode.text = ("0" + str(minutes)).right(2) + ":" + ("0" + str(seconds)).right(2) + ":" + ("0" + str(tenths)).right(2)

Unfortunately, it does not work.
It works instead whit the simple (but non suitable) form:

LabelNode.text = str(minutes) + ":" + str(seconds) + ":" + str(tenths)

Can anyone find the mistake I was not able to detect?

Thanks
David

:bust_in_silhouette: Reply From: DaveMS

I found myself the answer.
The easiest way to do it is:

LabelNode.text = "%02d:%02d:%02d" % [minutes, seconds, tenths]

You may select your own answer so others see problem is solved!

p7f | 2019-01-16 00:34

There’s also String.pad_zeros() and String.pad_decimals(), but that printf-style formatting method looks good too.

Calinou | 2019-01-16 08:32