Python的四舍五入与Excel的四舍五入不同吗?如何获得相同的结果?

huangapple go评论63阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月5日 19:50:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76406138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定