python: round 內建函式 (四捨五入)
阿新 • • 發佈:2019-01-10
Syntax
round(number[, ndigits=0])
對 number
進行 四捨五入:
Args :
number
:可正可負 。ngigits
:保留ngigits 位
小數 。
Test
assert round(0.5) == 1.0
assert round(-0.5) == -1.0
assert round(12345.678, -5) == 0.0
assert round(12345.678, -4) == 10000.0
assert round(12345.678, -3) == 12000.0
assert round(12345.678, -2) == 12300.0
assert round(12345.678, -1) == 12350.0
assert round(12345.678, 0) == 12346.0 == round(12345.678)
assert round(12345.678, 1) == 12345.7
assert round(12345.678, 2) == 12345.68
assert round(12345.678, 3) == 12345.678
assert round(12345.678, 4) == 12345.6780
round 陷阱
舉例
print round(1.045, 2)
print round(1.055 , 2)
列印結果:
1.04
1.05