05-数字四舍五入
17.2 数字四舍五入
在处理时间时,你经常会遇到小数点后有许多数字的浮点值。为了让这些值更易于处理,可以用Python内置的 round()
函数将它们缩短,该函数按照指定的精度四舍五入一个浮点数。只要传入要处理的数字,再加上可选的第二个参数,指明需要传入小数点后多少位即可。如果省略第二个参数, round()
会将数字四舍五入到最接近的整数。在交互式环境中输入以下代码:
>>> import time
>>> now = time.time()
>>> now
1543814036.6147408
>>> round(now, 2)
1543814036.61
>>> round(now, 4)
1543814036.6147
>>> round(now)
1543814037
导入 time
,并将 time.time()
保存在 now
中之后,我们调用 round(now, 2)
,来将 now
舍入到小数点后两位数字; round(now, 4)
舍入到小数点后4位数字; round(now)
舍入到最接近的整数。