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.
Since you don't want a decimal point for special cases, there is no formatting rule.
Workaround:
"{:04.1f}".format(number).replace(".0", "")
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With