round()不对齐浮点数

问题描述 投票:1回答:2

我不明白为什么会这样,值l/m不会被截断为小数点后两位小数...

root@OpenWrt:~# python3
Python 3.7.4 (default, Sep 15 2019, 18:13:03) 
[GCC 7.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> l = round((69.2222222/100),2)                  
>>> print(l)
0.68999999999999995
>>> type(l)
<class 'float'>
>>> m = 69.22222222/100
>>> print(m)
0.69222222220000007
>>> type(m)
<class 'float'>
>>> round(m,2)
0.68999999999999995

这会在使用(almost) full python3安装的自定义openWRT 18.6构建中发生。

为什么会这样?

我是否缺少任何包裹?

python rounding python-3.7 truncate openwrt
2个回答
0
投票

摘要:您得到的答案是正确的,但是没有正确打印。

1)答案是正确的。对于您的会话中的0.69和四舍五入的答案,底层的C double均相同:

>>> (0.68999999999999995).hex()
'0x1.6147ae147ae14p-1'
>>> (0.69).hex()
'0x1.6147ae147ae14p-1'

2)构建中的打印例程忽略了Python尽力显示最短的等效表示形式的努力。这是我系统上的同一会话:

Python 3.8.1 (v3.8.1:1b293b6006, Dec 18 2019, 14:08:53) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> l = round((69.2222222/100),2)
>>> print(l)
0.69
>>> m = 69.22222222/100
>>> print(m)
0.6922222222000001
>>> round(m, 2)
0.69

-1
投票

您可以创建自己的舍入函数

def round(v,i):
    a = v*10**i
    a = int(a)
    a = a/10**i
    return a

注意:此函数将在设置小数点后截断值

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