用前导零格式化包含小数点的数字 [英] Format a number containing a decimal point with leading zeroes

查看:44
本文介绍了用前导零格式化包含小数点的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用前导零格式化一个带有小数点的数字.

这个

<预><代码>>>>'3.3'.zfill(5)003.3

考虑所有数字甚至小数点.python中有没有只考虑整个部分的函数?

我只需要格式化不超过五位小数的简单数字.此外,使用 %5f 似乎考虑尾随而不是前导零.

解决方案

像你的例子那样从一个字符串开始,你可以写一个像这样的小函数来做你想做的事:

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

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?

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.

解决方案

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'

这篇关于用前导零格式化包含小数点的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆