用填充0s格式化Python中的浮点数

时间:2016-01-29 16:17:59

标签: python floating-point

Python,版本2.7.3在64位Ubuntu 12.04上

我有一个0到99.99之间的浮点数。 我需要以这种格式将其打印为字符串:

WW_DD

其中WW是整数,DD是舍入的小数点后2位数。 该字符串需要在前后填充0,以便始终采用相同的格式。

一些例子:

0.1    -->  00_10
1.278  -->  01_28
59.0   -->  59_00

我做了以下事情:

def getFormattedHeight(height):

    #Returns the string as:  XX_XX   For example:  01_25
    heightWhole = math.trunc( round(height, 2) )
    heightDec = math.trunc( (round(height - heightWhole, 2))*100 )
    return "{:0>2d}".format(heightWhole) + "_" + "{:0>2d}".format(heightDec)

除数字0.29外,效果很好,格式为00_28。

有人能找到适用于0到99.99之间所有数字的解决方案吗?

2 个答案:

答案 0 :(得分:4)

试试这个(在Python 2.7.10中测试):

compare

有关格式编号的背景信息,请参阅:https://pyformat.info/#number

帽子提示:How to format a floating number to fixed width in Python

答案 1 :(得分:1)

如果以这种方式计算heightDec,原始解决方案就有效:

heightDec = int(round((height - heightWhole)*100, 0))

首先乘以100,然后舍入并转换为int。