Pythonの四捨五入と切り上げと切り捨てのサンプルです。
| 確認環境 ・Python 3.7.2 |
目次
四捨五入(round)
四捨五入のサンプルです。
round関数を使用します。
# coding: utf-8
a = 2.26
print(round(a)) #2 小数第一位で四捨五入
print(round(a,1)) #2.3 小数第二位で四捨五入
b = 2.82
print(round(b)) #3 小数第一位で四捨五入
print(round(b,1)) #2.8 小数第二位で四捨五入
1つ目の引数は、対象の数値を指定します。
2つ目の引数は、位置を指定します。
※注意:round(2.675, 2) は、 2.68 ではなく 2.67 になります。バグではないと公式サイトに書いてあります。参照願います。https://docs.python.jp/3/library/functions.html#round
切り上げ(math.ceil)
切り上げのサンプルです。
# coding: utf-8
import math
a = 2.26
print(math.ceil(a)) #3
b = 2.82
print(math.ceil(b)) #3
2行目は、mathモジュールをインポートしています。
6,11行目は、math.ceilメソッドで切り上げをしています。
以下は、Python公式の数学関数のmathモジュールのリンクです。
https://docs.python.jp/3/library/math.html
切り捨て(math.floor)
切り捨てのサンプルです。
# coding: utf-8
import math
a = 2.26
print(math.floor(a)) #2
b = 2.82
print(math.floor(b)) #2
2行目は、mathモジュールをインポートしています。
6,11行目は、math.floorメソッドで切り捨てをしています。
以下は、Python公式の数学関数のmathモジュールのリンクです。
https://docs.python.jp/3/library/math.html
関連の記事
Python 計算のサンプル(演算/代入演算子)
Python 数値と文字列の変換のサンプル
Python 進数の変換のサンプル