Formatted output of numbers in a string

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By DimitriyPS
:warning: Old Version Published before Godot 3 was released.

I need to convert and display number in such a way that it has always taken 2 characters.

Let’s say we have a variable “n” which takes values from 0 to 99. If you run:

var n=1
print(str(n))

I can get the text to “1” while the need to “01”. However, if the variable “n” is >9, the “0” at the front not necessary to add.

How to do it?

:bust_in_silhouette: Reply From: jospic

var n = 1
n = "%02d" % [n]
print (n)

-j

It wasn’t my question, but thank you so much for the answer! I’m gonna use it.

ludosar | 2016-10-10 09:51

Don’t need to create an array for a single entry, i.e. "%02d" % n should also work.

ArdaE | 2019-01-21 10:14

:bust_in_silhouette: Reply From: genete
var n=1
print(str(n).pad_zeros(2))

Seems to be the clearest way to do it, thanks :slight_smile:

ocre | 2016-10-10 16:21

Oh whaaat?! And here I’ve been constructing number strings digit by digit.

rgrams | 2016-10-11 13:56