5

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.

BrtH
  • 2,610
  • 16
  • 27
  • https://stackoverflow.com/questions/2389846/python-decimals-format comes close btw, but isn't a duplicate since my leading zero requires a different answer. – BrtH Jan 23 '18 at 22:58
  • Possible duplicate of [Format a number containing a decimal point with leading zeroes](https://stackoverflow.com/questions/7407766/format-a-number-containing-a-decimal-point-with-leading-zeroes) – cacti5 May 22 '18 at 20:02

3 Answers3

6

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

Workaround:

"{:04.1f}".format(number).replace(".0", "")
Daniel
  • 42,087
  • 4
  • 55
  • 81
1

Hackish answer:

l = [1, 10, 1.1, 10.1, 1.1234]
s = lambda n: '{{{}}}'.format(':04.1f' if isinstance(n, float) else ':02').format(n)

for i in l:
    print(s(i))

# 01
# 10
# 01.1
# 10.1
# 01.1

The other two answers are both superior IMO. This is just a different approach.

r.ook
  • 13,466
  • 2
  • 22
  • 39
1

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))
Imran
  • 12,950
  • 8
  • 64
  • 79