[Python]round四舍五入精度缺失的解决
来源:互联网 发布:mac ppt自动播放设置 编辑:程序博客网 时间:2024/04/30 02:40
环境:
os: win7 64bit
python:2.7.5 32bit
对python四舍五入的解决方案
现象:
一般的四舍五入操作都是使用内置的round方法
In [14]: round(2.675,2)Out[14]: 2.67
文档中这样解释的
The documentation for the built-inround() function says that it rounds to the nearest value, rounding ties away from zero. Since the decimal fraction 2.675 is exactly halfway between 2.67 and 2.68, you might expect the result here to be (a binary approximation to) 2.68. It’s not, because when the decimal string2.675 is converted to a binary floating-point number, it’s again replaced with a binary approximation, whose exact value is
In [22]: Decimal(2.675)Out[22]: Decimal('2.67499999999999982236431605997495353221893310546875')
所以对于精度有明确要求的数学计算来说,使用round是不行的
google中有人这么解决的:
>>> from decimal import Decimal>>> n = Decimal('1.555')>>> round(n, 2)Decimal('1.56')##但是这个方法在2.7.5中已经不再适用了
现在使用的方式是:
可以使用str.format来格式化数字实现四舍五入
from decimal import DecimalIn [15]: '{:.2f}'.format(Decimal('2.675'))Out[15]: '2.68''
错误的写法
In [12]: '{:.2f}'.format(2.675)Out[12]: '2.67'
In [13]: '{:.2f}'.format('2.675')---------------------------------------------------------------------------ValueError Traceback (most recent call last)
In [14]: '{:.2f}'.format(Decimal(2.675))Out[14]: '2.67'
- [Python]round四舍五入精度缺失的解决
- Python 为什么不解决四舍五入(round)的“bug”
- JS中解决数值很小时四舍五入的精度问题
- JS中解决数值很小时四舍五入的精度问题
- bigDecimal的精度和四舍五入
- jquery解决小数点相加精度缺失问题
- json过程的精度缺失问题
- 让float 没有精度的缺失
- pch缺失的解决
- SQL的四舍五入ROUND函数
- Math.Round 不同的四舍五入
- Math.round()的四舍五入问题
- SQL的四舍五入ROUND函数
- Math.round四舍五入的理解
- python round函数并不是"四舍五入"
- python: round 内建函数 (四舍五入)
- Python缺失的{},永远的痛
- python下的四舍五入
- jvm 内存说明
- UESTC 1717 Journey(改)
- Launcher主要类的功能说明
- jvisual的使用
- ubuntu 10.10 下载android源码
- [Python]round四舍五入精度缺失的解决
- drawRect的使用
- 六个经典故事改变你的职业生涯 之1 你的心过门了吗?
- 数组分割
- paip.输入法编程---带ord gudin去重复-
- Activity生命周期,状态保存恢复(经典)
- 使用windows快捷键提高效率
- LeetCode - Binary Tree Inorder Traversal
- vim tab总结 http://blog.chinaunix.net/space.php?uid=16444831&do=blog&cuid=1137430