使用Python 3 *,您可以只使用
round(),因为除了舍入浮点数,当应用于整数时,它将始终返回一个int:
>>> num = 1.2345
>>> round(num,3)
1.234
>>> num = 1
>>> round(num,3)
1
帮助(float .__ round__)中记录了此行为:
Help on method_descriptor:
__round__(...)
Return the Integral closest to x, rounding half toward even.
When an argument is passed, work like built-in round(x, ndigits).
并帮助(int .__ round__):
Help on method_descriptor:
__round__(...)
Rounding an Integral returns itself.
Rounding with an ndigits argument also returns an integer.
*使用Python 2,round()始终返回一个浮点数.