0 votes

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

asked Jan 15, 2019 in Engine by DaveMS (78 points)

1 Answer

+3 votes
Best answer

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

LabelNode.text = "%02d:%02d:%02d" % [minutes, seconds, tenths]
answered Jan 15, 2019 by DaveMS (78 points)
selected Jul 16, 2019 by DaveMS

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

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.