Format a number containing a decimal point with leading zeroes

前端 未结 5 1335
南旧
南旧 2021-02-20 04:48

I want to format a number with a decimal point in it with leading zeros.

This

>>> \'3.3\'.zfill(5)
003.3

considers all the dig

5条回答
  •  南方客
    南方客 (楼主)
    2021-02-20 05:13

    Is that what you look for?

    >>> "%07.1f" % 2.11
    '00002.1'
    

    So according to your comment, I can come up with this one (although not as elegant anymore):

    >>> fmt = lambda x : "%04d" % x + str(x%1)[1:]
    >>> fmt(3.1)
    0003.1
    >>> fmt(3.158)
    0003.158
    

提交回复
热议问题