Python round 四捨五入用法與範例

本篇 ShengYu 介紹如何在 Python 四捨五入,在 Python 中要四捨五入的話要使用 round() 函式,接下來看看怎麼在 Python 中使用 round 來四捨五入吧!

如何在 Python 四捨五入

要在 Python 中四捨五入的用法很簡單,就是使用 round() 函式,
round() 會回傳 x 的數值的四捨五入結果

1
round(x)

實際操作個例子看看吧!

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
x1 = 4.2
x2 = 4.4
x3 = 4.6
x4 = 4.8
print(round(x1))
print(round(x2))
print(round(x3))
print(round(x4))

結果輸出如下,

1
2
3
4
4
4
5
5

那如果我要四捨五入到小數點第二位呢?
很簡單,直接在第二個參數帶入要到幾位數

1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
x1 = 4.222
x2 = 4.444
x3 = 4.666
x4 = 4.888
print(round(x1, 2))
print(round(x2, 2))
print(round(x3, 2))
print(round(x4, 2))

結果輸出如下,

1
2
3
4
4.22
4.44
4.67
4.89

Python 無條件進位

順便示範一下 Python 無條件進位,需要 import math

1
math.ceil(n)

實際操作個例子看看吧!

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
x1 = 4.2
x2 = 4.4
x3 = 4.6
x4 = 4.8
print(math.ceil(x1))
print(math.ceil(x2))
print(math.ceil(x3))
print(math.ceil(x4))

結果輸出

1
2
3
4
5
5
5
5

Python 無條件捨去

順便示範一下 Python 無條件捨去,需要 import math

1
math.floor(n)

實際操作個例子看看吧!

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import math
x1 = 4.2
x2 = 4.4
x3 = 4.6
x4 = 4.8
print(math.floor(x1))
print(math.floor(x2))
print(math.floor(x3))
print(math.floor(x4))

結果輸出

1
2
3
4
4
4
4
4

其他參考
Python運算: 無條件進位//四捨五入/無條件捨去 | CYL菜鳥攻略 - 點部落
https://dotblogs.com.tw/CYLcode/2020/03/12/113702
Python round()方法 - Python教學
http://tw.gitbook.net/python/number_round.html

有四捨六入五平分問題
四捨五入就用round( )?Python四捨五入的正確打開方式! - 台部落
https://www.twblogs.net/a/5baad9b12b7177781a0e9d5d
python3:小數位的四捨五入(用兩種方法解決round 遇5不進) - IT閱讀
https://www.itread01.com/content/1541696762.html
[Python] round() 四捨五入…的小坑 - 程式乾貨 - Medium
https://medium.com/%E7%A8%8B%E5%BC%8F%E4%B9%BE%E8%B2%A8/python-round-%E5%9B%9B%E6%8D%A8%E4%BA%94%E5%85%A5-%E7%9A%84%E5%B0%8F%E5%9D%91-7ef8accad931

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 新手入門教學懶人包
Python 讀檔,讀取 txt 文字檔
Python 字串分割 split
Python 取代字元或取代字串 replace
Python 產生 random 隨機不重複的數字 list
Python print 格式化輸出與排版
Python PIL 讀取圖片並顯示
Python OpenCV resize 圖片縮放