from decimal import Decimal
round(Decimal(0.123456789), 3) + Decimal(0.01) # out: Decimal('0.1330000000000000002081668171')
round(Decimal(0.123456789) + Decimal(0.01), 3) # out: Decimal('0.133')
测试环境 python 3.6.5 + ipython
:D
from decimal import Decimal
round(Decimal(0.123456789), 3) + Decimal(0.01) # out: Decimal('0.1330000000000000002081668171')
round(Decimal(0.123456789) + Decimal(0.01), 3) # out: Decimal('0.133')
测试环境 python 3.6.5 + ipython
:D
1
nooper Jul 22, 2019
不是 python 的坑,是所有计算机指令的问题。 你在好好查一下,有专门的文档 decimal round_up 等处理这个问题。
|
2
chenstack Jul 22, 2019 >>> round(Decimal('0.123456789'), 3) + Decimal('0.01')
Decimal('0.133') Decimal 初始化时不要传 float 类型,要传字符串,因为传 float 时,float 值本身就有精度丢失问题 >>> Decimal(0.01) Decimal('0.01000000000000000020816681711721685132943093776702880859375') >>> Decimal('0.01') Decimal('0.01') |
3
lyy16384 Jul 22, 2019
我试了没有 round 也一样
Decimal(0.123) + Decimal(0.01) |
4
chenstack Jul 22, 2019
Construct a new Decimal object. 'value' can be an integer, string, tuple, or another Decimal object. If no value is given, return Decimal('0'). The context does not affect the conversion and is only passed to determine if the InvalidOperation trap is active.
|
5
XIVN1987 Jul 22, 2019
使用 decimal 不就是为了避免 float 的误差吗?
对 decimal 使用 round 不就把精确表示又带回了 float 的不精确表示了吗? |
6
jingniao Jul 22, 2019 via Android
对 decimal round 有自己的函数
|
7
djj510620510 OP |
8
XIVN1987 Jul 22, 2019
@djj510620510
抱歉,我看错了,,我以为是把 decimal 加法结果传给了 round,, |
9
djj510620510 OP @jingniao 还真是。。。。
|
10
djj510620510 OP @jingniao 但按照 python 设计理念,不是应该 Decimal 类里实现一个__round__吗,然后这个__round__的逻辑跟 decimal.round 的逻辑一样。
|
11
hjq98765 Jul 22, 2019
我还是为是说 [四舍六入五成双]
|
12
djj510620510 OP @hjq98765 应该 JS 才会出现吧 /doge
|
13
pkuphy PRO >>> round(1.5)
2 >>> round(2.5) 2 |
14
poet00 Jul 22, 2019
`round(Decimal("0.123456789"), 3) + Decimal("0.01") #Decimal('0.133')`
``` from decimal import * getcontext().prec ``` 不是 decimal 的坑, 初始化 decimal 变量,推荐使用 string 或者在运算时手动指定 percesion |
15
1iuh Jul 22, 2019
初始化 decimal 别传浮点数进去
|
16
1iuh Jul 22, 2019
另外 decimal 有自己 round 方法。
|
17
hjq98765 Jul 22, 2019
|
18
azh7138m Jul 22, 2019
|
19
yushi17 Jul 22, 2019 via Android
|
20
5oiR5piv5YK76YC8 Jul 23, 2019
因为你传进去的时候就不是精确的
|