我想要显示:
49 as 49.00
and:
54.9和54.90
无论小数点的长度或是否有任何小数点,我想显示一个小数点后2位的小数,我想以一种有效的方式做到这一点。目的是展示货币价值。
例如,4898489.00
有关内置浮点类型的类似问题,请参阅将浮点数限制为两个小数点。
我想要显示:
49 as 49.00
and:
54.9和54.90
无论小数点的长度或是否有任何小数点,我想显示一个小数点后2位的小数,我想以一种有效的方式做到这一点。目的是展示货币价值。
例如,4898489.00
有关内置浮点类型的类似问题,请参阅将浮点数限制为两个小数点。
当前回答
你可以这样使用字符串格式化操作符:
num = 49
x = "%.2f" % num # x is now the string "49.00"
我不确定您所说的“高效”是什么意思——这几乎肯定不是应用程序的瓶颈。如果您的程序运行缓慢,请先对其进行分析,以找到热点,然后优化这些热点。
其他回答
Python文档中的字符串格式化操作部分包含了您正在寻找的答案。简而言之:
"%0.2f" % (num,)
一些例子:
>>> "%0.2f" % 10
'10.00'
>>> "%0.2f" % 1000
'1000.00'
>>> "%0.2f" % 10.1
'10.10'
>>> "%0.2f" % 10.120
'10.12'
>>> "%0.2f" % 10.126
'10.13'
你可以这样使用字符串格式化操作符:
num = 49
x = "%.2f" % num # x is now the string "49.00"
我不确定您所说的“高效”是什么意思——这几乎肯定不是应用程序的瓶颈。如果您的程序运行缓慢,请先对其进行分析,以找到热点,然后优化这些热点。
这与你可能已经看到的解决方案是一样的,但是这样做会更清楚:
>>> num = 3.141592654
>>> print(f“Number: {num:.2f}”)
如果你用这个来表示货币,并且还想用's来分隔值,你可以使用's
$ {:, .f2} .format (currency_value)。
例如:
Currency_value = 1234.50
$ {:,.f2}.format(currency_value)——> $ 1,234.50
下面是我不久前写的一段代码:
print(">在年底" + year_string + " total paid is \t$ {:,.2f}".format(total_paid))
> At the end of year 1 total paid is $ 43,806.36
> At the end of year 2 total paid is $ 87,612.72
> At the end of year 3 total paid is $ 131,419.08
> At the end of year 4 total paid is $ 175,225.44
> At the end of year 5 total paid is $ 219,031.80 <-- Note .80 and not .8
> At the end of year 6 total paid is $ 262,838.16
> At the end of year 7 total paid is $ 306,644.52
> At the end of year 8 total paid is $ 350,450.88
> At the end of year 9 total paid is $ 394,257.24
> At the end of year 10 total paid is $ 438,063.60 <-- Note .60 and not .6
> At the end of year 11 total paid is $ 481,869.96
> At the end of year 12 total paid is $ 525,676.32
> At the end of year 13 total paid is $ 569,482.68
> At the end of year 14 total paid is $ 613,289.04
> At the end of year 15 total paid is $ 657,095.40 <-- Note .40 and not .4
> At the end of year 16 total paid is $ 700,901.76
> At the end of year 17 total paid is $ 744,708.12
> At the end of year 18 total paid is $ 788,514.48
> At the end of year 19 total paid is $ 832,320.84
> At the end of year 20 total paid is $ 876,127.20 <-- Note .20 and not .2
在python 3中,这样做的一种方法是
'{:.2f}'.format(number)