简体   繁体   English

python中的格式数字,带有前导零和固定的小数位

[英]Format number in python with leading zeros and fixed decimal places

I am trying to format a number into a string in python. 我正在尝试将数字格式化为python中的字符串。 The result I hope for is for 0.1423 to be converted to 000.14 . 我希望将0.1423的结果转换为000.14 I tried 我试过了

num = 0.1423
print '%0.2f' %num

But this just results in the 0.14 . 但这只会导致0.14 I can't seem to get the leading zeros. 我似乎无法得到前导零。

Cheers, James 干杯,詹姆斯

num = 0.1423
print '%06.2f' %num

The six indicates the total field width and includes the decimal point. 六个表示字段的总宽度,包括小数点。 The zero indicates include leading zeros, the 2 indicates the precision. 零表示包括前导零,数字2表示精度。

The field width has to be provided as well to get the required number of leading zeros: 还必须提供字段宽度以获取所需的前导零个数:

print "%06.2f" % num

Output: 输出:

000.14

使用str.format

 print "{:06.2f}".format(num)

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

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