python 数字的四舍五入的问题

因为 python3 包括python2.7 之后的round策略使用的是decimal.ROUND_HALF_EVEN 
即Round to nearest with ties going to nearest even integer. 也就是只有在整数部分是奇数的时候, 小数部分才逢5进1; 偶数时逢5舍去。 这有利于更好地保证数据的精确性, 并在实验数据处理中广为使用。python

>>> round(2.55, 1) # 2是偶数,逢5舍去
2.5
>>> format(2.55, '.1f')
'2.5'

>>> round(1.55, 1) # 1是奇数,逢5进1
1.6
>>> format(1.55, '.1f')
'1.6'

 

但若是必定要decimal.ROUND_05UP 即Round away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise round towards zero. 也就是逢5必进1须要设置floatdecimal.Decimal, 而后修改decimal的上下文git

import decimal
from decimal import Decimal
context=decimal.getcontext() # 获取decimal如今的上下文
context.rounding = decimal.ROUND_05UP

round(Decimal(2.55), 1) # 2.6
format(Decimal(2.55), '.1f') #'2.6'

 

ps, 这显然是round策略问题, 不要扯浮点数在机器中的存储方式, 且不说在python里float, int 都是同decimal.Decimal同样是对象, 就算是数字, 难道设计round的人就这么无知以致于能拿浮点数直接当整数同样比较?!python2.7

相关文章
相关标签/搜索