开发者

Format a number containing a decimal point with leading zeroes

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 开发者_JAVA百科digits and even the decimal point. Is there a function in python that considers only the whole part?

I only need to format simple numbers with no more than five decimal places. Also, using %5f seems to consider trailing instead of leading zeros.


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


I like the new style of formatting.

loop = 2
pause = 2
print 'Begin Loop {0}, {1:06.2f} Seconds Pause'.format(loop, pause)
>>>Begin Loop 2, 0002.1 Seconds Pause

In {1:06.2f}:

  • 1 is the place holder for variable pause
  • 0 indicates to pad with leading zeros
  • 6 total number of characters including the decimal point
  • 2 the precision
  • f converts integers to floats


print('{0:07.3f}'.format(12.34))

This will have total 7 characters including 3 decimal points, ie. "012.340"


Like this?

>>> '%#05.1f' % 3.3
'003.3'


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'


With Python 3.6+ you can use the fstring method:

f'{3.3:.0f}'[-5:]
>>> '3'

f'{30000.3:.0f}'[-5:]
>>> '30000'

This method will eliminate the fractional component (consider only the whole part) and return up to 5 digits. Two caveats: First, if the whole part is larger than 5 digits, the most significant digits beyond 5 will be removed. Second, if the fractional component is greater than 0.5, the function will round up.

f'{300000.51:.0f}'[-5:]
>>>'00001'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜