风言枫语  

环境:

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-in round() 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 string 2.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 Decimal
In [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'


 

 



 

 

posted on   风言枫语  阅读(1561)  评论(1编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
 
点击右上角即可分享
微信分享提示