简体   繁体   English

格式化包含带前导零的小数点的数字

[英]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 digits and even the decimal point.考虑所有数字甚至小数点。 Is there a function in python that considers only the whole part? python 中是否存在仅考虑整个部分的 function?

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.此外,使用%5f似乎考虑了尾随而不是前导零。

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:06.2f} 中:

  • 1 is the place holder for variable pause 1 是变量暂停的占位符
  • 0 indicates to pad with leading zeros 0 表示用前导零填充
  • 6 total number of characters including the decimal point包括小数点在内的 6 个字符总数
  • 2 the precision 2 精度
  • f converts integers to floats f 将整数转换为浮点数

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'
print('{0:07.3f}'.format(12.34))

This will have total 7 characters including 3 decimal points, ie.这将有总共 7 个字符,包括 3 个小数点,即。 "012.340" “012.340”

With Python 3.6+ you can use the fstring method:使用 Python 3.6+,您可以使用 fstring 方法:

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.此方法将消除小数部分(仅考虑整个部分)并返回最多 5 位数字。 Two caveats: First, if the whole part is larger than 5 digits, the most significant digits beyond 5 will be removed.两个警告:首先,如果整个部分大于 5 位,则超过 5 位的最高有效位将被删除。 Second, if the fractional component is greater than 0.5, the function will round up.其次,如果小数部分大于 0.5,则 function 将四舍五入。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM