Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python formatting leading zeros and optional decimals

Tags:

python

I'm trying to format some numbers in Python in the following way:

(number) -> (formatted number)
1 -> 01
10 -> 10
1.1 -> 01.1
10.1 -> 10.1
1.1234 -> 01.1

What formatting specification could I use for that?

What I've tried: {:04.1f} doesn't work correctly if there's no decimal part, while {:0>2} only works for integers, {:0.2g} comes close but doesn't add the leading zero and {:0>4.2g} adds too many zeroes if there's no decimal part.

like image 585
BrtH Avatar asked Mar 07 '23 02:03

BrtH


2 Answers

Since you don't want a decimal point for special cases, there is no formatting rule.

Workaround:

"{:04.1f}".format(number).replace(".0", "")
like image 154
Daniel Avatar answered Mar 09 '23 17:03

Daniel


I would branch on whether your number is an integer or a float:

if isinstance(number, int):
    print('{:0>2}'.format(number))
elif isinstance(number, float):
    print('{:04.1f}'.format(number))
like image 26
Imran Avatar answered Mar 09 '23 16:03

Imran