菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 基础教程
(追記) (追記ここまで)

Python round() 函数

Python 数字 Python 数字


描述

round() 方法返回浮点数x的四舍五入值。


语法

以下是 round() 方法的语法:

round( x [, n] )

参数

  • x -- 数值表达式。
  • n -- 数值表达式,表示从小数点位数。

返回值

返回浮点数x的四舍五入值。

实例

以下展示了使用 round() 方法的实例:

实例

#!/usr/bin/python

print "round(80.23456, 2) : ", round(80.23456, 2)
print "round(100.000056, 3) : ", round(100.000056, 3)
print "round(-100.000056, 3) : ", round(-100.000056, 3)

以上实例运行后输出结果为:

round(80.23456, 2) : 80.23
round(100.000056, 3) : 100.0
round(-100.000056, 3) : -100.0

Python 数字 Python 数字

AI 思考中...

2 篇笔记 写笔记

  1. #0
    552

    在实际使用中发现round函数并不总是如上所说的四舍五入。如:

    In [14]: round(2.355, 2)
    Out[14]: 2.35

    注:环境为 python3.5.2

    因为该函数对于返回的浮点数并不是按照四舍五入的规则来计算,而会收到计算机表示精度的影响。

    关于该问题搜索后解释比较清楚的文章地址如下:http://www.runoob.com/w3cnote/python-round-func-note.html

    9年前 (2017年09月30日)
  2. #0

    Peng Boyu

    pen***[email protected]

    390

    当参数n不存在时,round()函数的输出为整数

    当参数n存在时,即使为0,round()函数的输出也会是一个浮点数

    此外,n的值可以是负数,表示在整数位部分四舍五入,但结果仍是浮点数

    例如:

    print(round(123.45))
    print(round(123.45,0))
    print(round(123.45,-1))

    结果是:

    123
    123.0
    120.0

    Peng Boyu

    pen***[email protected]

    6年前 (2020年12月28日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /