您的位置首页生活百科

python中round的用法

python中round的用法

的有关信息介绍如下:

python中round的用法

python标准库的解释及翻译

round(number[,ndigits])

Return the floating point valuenumberrounded tondigitsdigits after the decimal point.Ifndigitsis omitted, it returns the nearest integer to its input.Delegates tonumber.__round__(ndigits).

For the built-in types supportinground(), values are rounded to the closest multiple of 10 to the power minusndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, bothround(0.5)andround(-0.5)are0, andround(1.5)is2).The return value is an integer if called with one argument, otherwise of the same type asnumber.

Note

The behavior ofround()for floats can be surprising: for example,round(2.675,2)gives2.67instead of the expected2.68.This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float.SeeFloating Point Arithmetic: Issues and Limitationsfor more information.

返回number舍入到小数点后ndigits位的浮点值。如果省略ndigits,将返回最接近输入的整数。底层调用的是number.__round__(ndigits)。

对于支持round()的内建类型,值舍入到10的最接近的负ndigits次幂的倍数;如果离两个倍数的距离相等,则舍入选择偶数(因此,round(0.5)和round(-0.5)都是0,而round(1.5)是2)。如果使用一个参数调用返回值是一个整数,否则其类型与number相同。

注意

浮点数round()的行为可能让人惊讶,例如round(2.675,2)给出的是2.67而不是期望的2.68。这不是一个错误:因为事实上大部分十进制小数不能用浮点数精确表示。更多信息,请参阅浮点数运算:问题和限制。

round简介

round(number[,ndigits])

对浮点数进行近似取值,保留几位小数。

第一个参数是一个浮点数,第二个参数是保留的小数位数,可选,如果不写的话默认保留到整数

round用法举例

>>> round(1.34)

1

>>> round(1.34,1)

1.3

>>> round(-1.34)

-1

>>> round(-1.34,1)

-1.3

>>> round(3.4)

3

>>> round(3.5)

4

>>> round(3.6, 0)

4.0

>>> round(3.5, 0)

4.0

>>> round(1.95583, 2)

1.96

>>> round(1241757, -3)

1242000

>>> round(5.045, 2)

5.04

>>> round(5.055, 2)

round()使用注意点

1、第二个参数值为负数时,

>>> round(123456,-2)

123500

>>> round(123456,-3)

123000

>>> round(123.456,-1)

120.0

2、特殊数字round出来的结果可能未必是想要的。

>>> round(2.675, 2)

2.67

这是因为浮点数在计算机内部的储存是二进制,并不是精确的,2.675转换成二进制后比十进制的2.675要稍小,更接近2.67而不是2.68