37,721
社区成员
发帖
与我相关
我的任务
分享
>>> round(1.5)
2
>>> round(2.5)
2
>>> round(3.5)
4
>>> round(4.5)
4
>>> round(5.5)
6
>>> round(6.5)
6
>>> round(0.05, 1)
0.1
>>> round(0.15, 1)
0.1
>>> round(0.25, 1)
0.2
>>> round(0.35, 1)
0.3
>>> round(0.45, 1)
0.5
由于 python3 包括python2.7 以后的round策略使用的是decimal.ROUND_HALF_EVEN
即Round to nearest with ties going to nearest even integer. 也就是只有在整数部分是奇数的时候, 小数部分才逢5进1;
偶数时逢5舍去。 这有利于更好地保证数据的精确性, 并在实验数据处理中广为使用。
python3.5的文档是这么说明的:
“values are rounded to the closest multiple of 10 to the power minus ndigits;
if two multiples are equally close, rounding is done toward the even choice.”
如果距离两边一样远,会保留到偶数的一边。
比如round(0.5)和round(-0.5)都会保留到0,而round(1.5)会保留到2。
>>> round(2.675, 2)
2.67
>>> '{:.2f}'.format(Decimal('2.675'))
'2.68'
>>> '{:.2f}'.format(Decimal(str(2.675)))
'2.68'
>>>
在脚本中处理财务数据时候可以用下面的标准方式.
import decimal
from decimal import Decimal
context=decimal.getcontext() # 获取decimal现在的上下文
context.rounding = decimal.ROUND_05UP
print(round(Decimal(2.55), 1)) # 2.6
print(format(Decimal(2.55), '.1f')) #'2.6'
Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import decimal
>>> from decimal import Decimal
>>> context=decimal.getcontext()
>>> context.rounding = decimal.ROUND_05UP
>>> round(2.55,1)
2.5
>>> print(round(Decimal(2.55), 1)) # 2.6
2.6
>>> print(format(Decimal(2.55), '.1f')) #'2.6'
2.6
>>>