Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python3中,round(395,-2)的工作原理是什么?_Python_Python 3.x - Fatal编程技术网

在Python3中,round(395,-2)的工作原理是什么?

在Python3中,round(395,-2)的工作原理是什么?,python,python-3.x,Python,Python 3.x,我执行了round(395,-2)并将400作为输出返回。这是如何工作的?在您提供的示例中,round(395,-2)表示从395到最接近的100 函数round将所需的精度作为第二个参数。负精度表示要删除小数点之前的有意义数字 round(123.456, 3) # 123.456 round(123.456, 2) # 123.45 round(123.456, 1) # 123.4 round(123.456, 0) # 123.0 round(123.456, -1) # 120

我执行了
round(395,-2)
并将
400
作为输出返回。这是如何工作的?

在您提供的示例中,
round(395,-2)
表示从395到最接近的100

函数
round
将所需的精度作为第二个参数。负精度表示要删除小数点之前的有意义数字

round(123.456, 3)  # 123.456
round(123.456, 2)  # 123.45
round(123.456, 1)  # 123.4
round(123.456, 0)  # 123.0
round(123.456, -1) # 120.0
round(123.456, -2) # 100.0
round(123.456, -3) # 0.0

这是有意的。负值将四舍五入为10的幂-1圈到最近的10圈,-2圈到最近的100圈,以此类推。参见

将数字四舍五入到给定的十进制精度(默认为0位)。 这总是返回一个浮点数。精度可能为负。当它为负数时,四舍五入到10的次方,这里是
-2
,它将四舍五入到
100
。因此
395
将四舍五入到最近的
100
,即
400

四舍五入的不同方法

使用内置函数round():

或内置函数格式():

或新样式字符串格式:

"{:.2f}".format(1.2345)
'1.23
"%.2f" % (1.679)
'1.68'
或旧式字符串格式:

"{:.2f}".format(1.2345)
'1.23
"%.2f" % (1.679)
'1.68'

看一看:@RafaelC这不适用于此我很好奇你期望什么
"%.2f" % (1.679)
'1.68'