Python round() Functions are another useful onePython內置函數,Can be used when doing computational work.round()The first parameter of the function is a number,是必須的.round()The function can also accept an integer as an optional second input,Specify the number after the decimal point,以便四捨五入.當函數運行時,Returns the rounded value of the first input.If you don't provide a second input,Or its value is zero,The function rounds the given number to the nearest integer.If a second input is provided,The function rounds the given number to the specified number of decimal places.換句話說,when a second input is provided,round()Rounds the given number to the nearest five10Negative of the nearest multiple of N的冪,Nis the second input.We can take a look now round() 函數在 Python 中如何工作的幾個例子.
在 round() in the first example of the function,We can pass a simple negative float.Note that we only provide one parameter to the function,We omitted the optional second parameter.我們可以看到,對-2.8的值應用round()產生的值是-3.
In example two,這一次我們在 round() An optional second parameter is added to the function.這裡我們把 -3.67 作為第一個參數,把 1 作為第二個參數.This produces a result:-3.7.
使用 round() The third example of the function shows us testing two decimal places during rounding.傳入-4.877,第二個參數是2,結果是-4.88.
Any article that discusses mathematics without mentioning some formPi,都是不完整的.在例四中,我們把 3.14 作為第一個參數,把 1 作為第二個參數.這裡的結果是3.1.
在Python round()in the fifth example of the function,我們將3.141捨入到小數點後兩位.We got what was expected3.14作為函數的輸出.
Here we build on the previous example,No longer round to two decimal places,Instead, it rounds up to three digits.該函數的第一個參數是 3.1415,第二個參數是 3.這個 round() 調用的結果是 3.142.
round()The last example is to enter numbers27.918273645and round to the nearest decimal point4位.我們得到的結果是27.9183.
Pythonround()函數返回一個浮點數,It is the rounded version of the given number,Has the specified number of decimal places.默認情況下,The number of decimal points is0.因此,如果你調用 round() when there is no second parameter,The function will return the nearest integer.