Python 3.5.0 十进制

Python 3.5.0 decimal

所以我需要在输出中去掉一些小数部分。

我有以下行:

print ("O valor a pagar é de ", ***float(n3)*1.3***, " euros.")

在我突出显示的区域中,我遇到了很多情况...输出是这样的,例如:2,47893698236923 我希望它只显示 2 个小数点,例如:2,47 .

我该怎么做?我正在使用 python 3.5.0

使用round()函数。

print("O valor a pagar é de ", round(float(n3) * 1.3, 2), " euros.")

根据你给出的例子,你想截断一个值(此时其他答案都会对值进行四舍五入)。如果您只想截断,我会使用字符串切片。

>>> num = 2.47893698236923
>>> str(num)[:str(num).find('.') + 3]
'2.47'

PS:如果你不知道那里是否会有小数,你可以使用这个变体:

>>> numstr = str(num)
>>> numstr[:(numstr.find('.') + 3) if numstr.find('.') else None]
'2.47'

正如 BlivetWidget 所指出的,浮动格式导致舍入而不是截断。

您可以使用十进制模块:

from decimal import Decimal, ROUND_DOWN

x = 2.47893698236923
print(Decimal(str(x)).quantize(Decimal('.01'), rounding=ROUND_DOWN))
print(Decimal(str(x)).quantize(Decimal('.001'), rounding=ROUND_DOWN))

输出:

2.47
2.478

编辑 正如 Python docs 解释的那样:

The quantize() method rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of places

编辑 2

另见 Truncating floats in Python