I executed round(395,-2)
and it returned 400
as a output.How this thing worked.?
答案 0 :(得分:3)
In the example you provided, round(395, -2)
means round 395 to the nearest hundred.
The function round
takes the precision you want as second argument. Negative precision means you want to remove significative digits before the decimal point.
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
答案 1 :(得分:1)
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative. When its negative it rounds off to the power of 10, here its -2
and it will round off to 100
. so 395
will be round off to nearest 100
which is 400
.
Different ways to round off
Use the built-in function round():
round(1.2345,2)
1.23
Or built-in function format():
format(1.2345, '.2f')
'1.23'
Or new style string formatting:
"{:.2f}".format(1.2345)
'1.23
Or old style string formatting:
"%.2f" % (1.679)
'1.68'
答案 2 :(得分:0)
This is intended. A negative value will round to a power of 10. -1 rounds to the nearest 10, -2 to the nearest 100, etc. See https://docs.python.org/2/library/functions.html#round