Format a number containing a decimal point with leading zeroes

前端 未结 5 1303
南旧
南旧 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:02

    Starting with a string as your example does, you could write a small function such as this to do what you want:

    def zpad(val, n):
        bits = val.split('.')
        return "%s.%s" % (bits[0].zfill(n), bits[1])
    
    >>> zpad('3.3', 5)
    '00003.3'
    

提交回复
热议问题