我想要显示:

49 as 49.00

and:

54.9和54.90

无论小数点的长度或是否有任何小数点,我想显示一个小数点后2位的小数,我想以一种有效的方式做到这一点。目的是展示货币价值。

例如,4898489.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"

我不确定您所说的“高效”是什么意思——这几乎肯定不是应用程序的瓶颈。如果您的程序运行缓慢,请先对其进行分析,以找到热点,然后优化这些热点。

我猜你可能正在使用Decimal模块中的Decimal()对象?(如果对于任意大的数字,你需要精确到小数点后两位的精度,你绝对应该这样做,这就是你问题的标题所暗示的…)

如果是这样,文档的Decimal FAQ部分有一个可能对你有用的问题/答案对:

Q.在有两位小数点的定点应用程序中,有些输入有很多位,需要四舍五入。其他的不应该有多余的数字,需要验证。应该使用什么方法? a . quantize()方法舍入到小数点后的固定位数。如果设置了Inexact陷阱,它对验证也很有用:

>>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
   ...
Inexact: None

下一个问题是

问:一旦我有了有效的两地输入,我如何在整个应用程序中保持这个不变式?

如果您需要答案(以及许多其他有用的信息),请参阅文档中前面提到的部分。同样,如果你保持你的小数有两位精度超过小数点(意味着尽可能多的精度是必要的,以保持所有的数字在小数点的左边,两个在它的右边,没有更多的…),然后用str将它们转换为字符串将很好:

str(Decimal('10'))
# -> '10'
str(Decimal('10.00'))
# -> '10.00'
str(Decimal('10.000'))
# -> '10.000'

你应该使用新的格式规范来定义你的值应该如何表示:

>>> from math import pi  # pi ~ 3.141592653589793
>>> '{0:.2f}'.format(pi)
'3.14'

文档有时可能有点迟钝,所以我推荐以下更容易阅读的参考:

Python字符串格式烹饪书:展示了新风格的.format()字符串格式的示例 Pyformat.info:比较老式的%字符串格式和新式的.format()字符串格式

Python 3.6引入了字面值字符串插值(也称为f-strings),所以现在你可以把上面的代码写得更简洁:

>>> f'{pi:.2f}'
'3.14'
>>> print "{:.2f}".format(1.123456)
1.12

你可以把2f中的2改成你想显示的任何小数点。

编辑:

在Python3.6中,它转换为:

>>> print(f"{1.1234:.2f}")
1.12

.format是一种可读性更好的处理变量格式化的方式:

'{:.{prec}f}'.format(26.034, prec=2)

是什么

print round(20.2564567 , 2)    >>>>>>>        20.25


print round(20.2564567 , 4)    >>>>>>>        20.2564

如果你有多个参数,你可以使用

 print('some string {0:.2f} & {1:.2f}'.format(1.1234,2.345))
 >>> some string 1.12 & 2.35

在python 3中,这样做的一种方法是

'{:.2f}'.format(number)

最简单的例子是:

代码:

>>>分= 19.5分 >>> total = 22 >>>'正确答案:{:.2%}'.format(分数/总分) `

输出:正确答案:88.64%

如果你用这个来表示货币,并且还想用'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

这与你可能已经看到的解决方案是一样的,但是这样做会更清楚:

>>> num = 3.141592654

>>> print(f“Number: {num:.2f}”)

OP总是希望显示两个小数点后的位置,因此像所有其他答案所做的那样,显式地调用格式化函数是不够的。

正如其他人已经指出的那样,Decimal适用于货币。但是Decimal显示了所有的小数点。因此,重写它的显示格式化器:

class D(decimal.Decimal):
    def __str__(self):
        return f'{self:.2f}'  

用法:

>>> cash = D(300000.991)
>>> print(cash)
300000.99

简单。

编辑:

显示小数点后至少两位,但不截断有效数字:

class D(decimal.Decimal):
    def __str__(self):
        """Display at least two decimal places."""
        result = str(self)
        i = result.find('.')
        if i == -1:
             # No '.' in self. Pad with '.00'.
             result += '.00'
        elif len(result[i:]) == 2:
             # One digit after the decimal place. Pad with a '0'.
             result += '0'
        return result

我希望Python的未来版本将改进数字格式,以允许最小的小数位数。类似于Excel数字格式中的#符号。