Python保留小数的方法
因总是忘记保留小数的方法,故在此做个总结。
方法一:字符串格式化
>>> print('%.2f' % 1.255)
1.25
方法二:format函数方法
format函数有两种写法
1、使用占位符(需注意占位符和冒号不能丢),此方法可以一次输出多个
>>> print('{:.2f}, {:.3f}'.format(1.256, 1.2635))
1.26, 1.264
2、不使用占位符,此方法只能一次输出一个,并且需要格式化的数字在前
>>> print(format(1.235, '.2f'))
1.24
方法三:round函数
round函数返回浮点数的四舍五入值,第一个参数是浮点数,第二个参数是保留的小数位数,不写默认保留到整数。但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
方法四: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')