关于 python 四舍五入的问题

2014-05-29 15:03:11 +08:00
 forreal
初学python

import decimal
a = decimal.Decimal("0.5")
decimal.getcontext().rounding = decimal.ROUND_UP

print(round(a))

如何能让a四舍五入到1?
用的是python3
7329 次点击
所在节点    Python
13 条回复
imn1
2014-05-29 15:14:37 +08:00
转贴网上收集
google中有人这么解决的:

>>> from decimal import Decimal
>>> n = Decimal('1.555')
>>> round(n, 2)
Decimal('1.56')

现在使用的方式是:
可以使用str.format来格式化数字实现四舍五入

from decimal import Decimal
In [15]: '{:.2f}'.format(Decimal('2.675'))
Out[15]: '2.68''





def myround(par,l):
temp = 1
for i in range(l):
temp*=10
v = int((par+0.5/temp)*temp) / temp
return v

i = 1.25
print(myround(i,1))
i = 1.245
print(myround(i,2))
i = 1.21
print(myround(i,1))
i = 1.249
print(myround(i,2))

----
1.3
1.25
1.2
1.25
forreal
2014-05-29 15:27:52 +08:00
@imn1
也就是说没有现成的函数?
myround那个不错
riaqn
2014-05-29 15:30:15 +08:00
imn1
2014-05-29 16:28:42 +08:00
@forreal 这个是浮点数精度问题,例如0.5实际上是0.49xxxxxxxxxxxxxx,四舍五入当然就是用了“舍”,
0.5只是字面精度,所以上面用了字串方式处理也是合理的
forreal
2014-05-29 16:39:53 +08:00
@imn1
字符串换成2.665就不对了

from decimal import Decimal
a = '{:.2f}'.format(Decimal('2.665'))
print(a)
imn1
2014-05-29 17:09:23 +08:00
还真是呢,之前都是看,保存笔记,没怎么验证,实际应用也很少用到四舍五入
lynx
2014-05-29 18:47:00 +08:00
In [1]: import math

In [2]: math.ceil(0.5)
Out[2]: 1
forreal
2014-05-29 18:59:23 +08:00
@lynx
ceil函数貌似是向上近似,不是四舍五入
import math
a = math.ceil(0.4)
print(a)
结果也是1
hahastudio
2014-05-29 21:05:52 +08:00
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import decimal
>>> a = decimal.Decimal("0.5")
>>> decimal.getcontext().rounding = decimal.ROUND_UP
>>> print round(a)
1.0

感觉 @riaqn 是正解,是Python 3的round函数对策略做了调整
这个取整是“四舍六入五留双” http://zh.wikipedia.org/zh-cn/%E6%95%B0%E5%80%BC%E4%BF%AE%E7%BA%A6
我记得第一次见到这种取整规则是在大物实验上= =
rrfeng
2014-05-29 21:26:16 +08:00
math 里好像有来着
forreal
2014-05-30 00:21:00 +08:00
@hahastudio
涨知识了
SimbaPeng
2017-07-13 12:50:57 +08:00
上面都没说到关键点,你这个代码绝对可以实现标准的四舍五入不丢失精度,不过为什么你没有得到 1,是因为 round 函数如果省略掉第二个参数将会永远返回 int 类型,而你的 a 是 Decimal 对象,所以你要这样写才能得到 1:
print(round(a, 0))
linhua
2017-07-18 16:07:05 +08:00
@SimbaPeng
这个是 向上取整, 你可以试试 0.1

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/114880

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX