LoginSignup
16
12

More than 3 years have passed since last update.

Python3での四捨五入、切り捨て、切り上げ。

Last updated at Posted at 2019-07-18

初投稿になります。
指摘等あれば、よろしくお願いします。

はじめに

Pythonを勉強する中で、丸め処理を行う関数が複数あり混乱したので、自分への備忘録としてまとめておきます。

実証環境

・Python3.7.1

実行コードとその出力は次のように示します。

example.py
print('出力')
#出力

round関数

四捨五入に近い処理を行う関数。
基本的には四捨五入を行います。
第二引数で丸め後の桁を指定することができます。

round_1.py
print(round(3.1415, 2))
#3.14

print(round(3.1415, 1))
#3.1

また、第二引数を指定しない場合は最も近い整数となるようです。

round_2.py
print(round(1.4142))
#1

print(round(1.7320))
#2

round関数の注意点

私が混乱した原因です(笑)

round関数は基本的には四捨五入を行いますが、違う挙動をする場合があります。
例えば以下の例です。

round_3.py
print(round(1.5))
#2

print(round(2.5))
#2

print(round(3.5))
#4

2.5という数に対して、四捨五入であれば本来は3を出力しなければいけません。
しかし、ここでは2を出力しています。

この例のように、round関数は数から最も近い整数が2つ存在する場合(この場合は2と3が存在する)、結果が偶数となる方へ丸め処理を行います。

math.floor関数

切り捨てを行う関数。
小数点以下を切り捨て、整数へと丸める処理を行うようです。

floor.py
import math

print(math.floor(1.1421))
#1
print(math.floor(1.7320))
#1
print(math.floor(1.5))
#1
print(math.floor(2.5))
#2
print(math.floor(3.5))
#3

math.ceil関数

切り上げを行う関数。
小数点以下を切り上げ、整数へと丸める処理を行うようです。

ceil.py
import math

print(math.ceil(1.1421))
#2
print(math.ceil(1.7320))
#2
print(math.ceil(1.5))
#2
print(math.ceil(2.5))
#3
print(math.ceil(3.5))
#4

あとがき

これから自分が使いそうなものをまとめてみました。

初投稿ということもあり、拙い文章になってしまいましたが、ここまで読んでいただきありがとうございます。
ご指摘等あればよろしくお願いします。

16
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
12