无需浮点运算的精确乘法

问题描述 投票:0回答:3

如何获得乘法的准确结果?

Python 告诉我

0.017 * 3
等于
0.051000000000000004
。有没有命令可以让python打印
0.051

python precision multiplication
3个回答
2
投票

假设您知道该操作应输出的预期有效数字位数,您可以使用 python 中的内置舍入函数(在本例中为 3)。

>>> round(0.017 * 3, 3)
0.051

2
投票

Python 中的小数数字文字的类型为

float
,以二进制表示。使用
Decimal
类型进行以 10 为底的算术运算。

>>> from decimal import Decimal
>>> print(Decimal('0.017') * 3)
0.051

0
投票

当我想要在 fstring 文本中显示百分比时,我遇到了这个问题,并且有一个使用 fstrings 格式的很好的解决方案。它在技术上与

round()
解决方案相同,但比必须向 fstrings 中的每个百分比添加舍入函数更容易维护。

number = 0.1433
print(f"the percent is {number*100}%")
print(f"the percent is {number:.1%}")

the percent is 14.330000000000002%
the percent is 14.3%

请参阅如何打印百分比值?了解更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.