Python保留小数的方法

因总是忘记保留小数的方法,故在此做个总结。

方法一:字符串格式化

>>> print('%.2f' % 1.255)
1.25

# 补充左侧补0
>>> print('%03d' % 7)
007

方法二:format函数方法
format函数有两种写法
1、使用占位符(需注意占位符和冒号不能丢),此方法可以一次输出多个

>>> print('{:.2f}, {:.3f}'.format(1.256, 1.2635))
1.26, 1.264

# 左侧补0
>>> print('{:02d}'.format(5))
05

2、不使用占位符,此方法只能一次输出一个,并且需要格式化的数字在前

>>> print(format(1.235, '.2f'))
1.24

# 左侧补0
>>> print(format(9, '05d'))
00009

方法三:round函数
round函数返回浮点数的四舍五入值,第一个参数是浮点数,第二个参数是保留的小数位数,不写默认保留到整数;

>>> print(round(1.2345, 3))
1.234
>>> print(round(1.23456, 3))
1.235
>>> print(round(2.5))
2
>>> print(round(3.5))
4

但round函数有坑,在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(3.332, 2)    # 3.332保留两位小数,3.332距离3.33更近(0.002),距离3.34较远(0.008),因此保留到3.33
3.33
>>> round(3.337, 2)    # 3.337保留两位小数,3.337距离3.34更近(0.003),距离3.33较远(0.007),因此保留到3.34
3.34

另外,在机器中浮点数不一定能精确表达,“换算成1和0后,可能是无限位数的,而机器会进行截断处理”,因此实际在机器中的浮点数与我们看到的并不完全一致,在机器中保存的比实际的数字大一点或者小一点,而round函数是保留到离上一位更近的一端,因此如果对精确度要求高的话,不建议使用。

>>> round(2.265, 2)
2.27
>>> round(2.275, 2)
2.27
>>> round(2.285, 2)
2.29

方法四:decimal模块
decimal意思为十进制,这个模块提供了十进制浮点数运算支持,可以给Decimal传递整型或字符串参数,但不能是浮点数数据,因为浮点数本身就不准确。该模块遵循四舍五入

>>> from decimal import Decimal
>>> Decimal('1.23456').quantize(Decimal('0.000'))
Decimal('1.235')
>>> Decimal(123).quantize(Decimal('0.0'))
Decimal('123.0')
posted @ 2022-02-10 14:03  hook_what  阅读(7110)  评论(0编辑  收藏  举报