英文:
Why Python round-off is different from the excel round off? How to get the same result
问题
我面临一个关于Python四舍五入的问题。
输入值 = 3.7145,
我在Excel中尝试了以下公式:
formula: =round(C9/1000,6)
我得到了以下输出 = 0.003715,
同样的事情,当我在Python中尝试以下代码时:
Python 代码:
number = 3.7145
result = round(number / 1000, 6)
print(result)
输出:
0.003714
如何确保我们得到完全相同的值,因为我的需求是高精度的,所以甚至不允许有0.000001的变化。
我已经尝试了其他数字,在Excel和Python中得到了相同的值:
输入:1.0127、2.3216、5.4938
输出:0.001013、0.002322、0.005494(在Python和Excel中都相同)
英文:
I am facing an issue with python round-off.
Input value = 3.7145,
which I have tried in excel with the
formula: =round(C9/1000,6)
and I get the
Output = 0.003715,
Same thing when I tried with Python with the below code:
Python Code:
number = 3.7145
result = round(number / 1000, 6)
print(result)
Output:
0.003714
How to ensure that we get exact same value, as my requirement is a high precision so even a .000001 variation is not allowed.
I have tried same with other number also where I get the same values in excel and python
Input : 1.0127, 2.3216, 5.4938
Output: 0.001013, 0.002322, 0.005494 (Same in python & excel)
答案1
得分: 1
如果您希望获得更高的精确度,应该使用 Decimal
而不是 Float
。
Python 代码
from decimal import Decimal
number = Decimal("3.7145")
result = number / 1000
print(round(result, 6))
输出
0.003715
英文:
If you want to get better precision you should use Decimal
instead of Float
Python Code
from decimal import Decimal
number = Decimal("3.7145")
result = number / 1000
print(round(result, 6))
Output
0.003715
Edit 2021.06.05 17:51 UTC
Changed number = Decimal(3.7145)
to number = Decimal("3.7145")
As @RonRosenfeld mentioned in a comment creating number
as Decimal(3.7145)
includes inaccuracy of floating point from 3.7145
float number
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论