LoginSignup
1
1

More than 1 year has passed since last update.

【Python3】Decimal.quantizeを用いて小数点第○位以下を四捨五入

Last updated at Posted at 2022-11-13

何の記事?

Python3で小数点以下を丸める関数にroundがありますが、
浮動小数点演算の問題により四捨五入が正確に行われない
場合があります。

f = 2.675
 
print(round(f, 2))

実行結果:

2.67

本当は2.68にならなければなりませんが切り捨てされてしまっています。この事象に対する対策です。

Decimalを用いる方法

Decimalを用います。

from decimal import Decimal, ROUND_HALF_UP

def my_round(x, d=2):
    p = Decimal(str(x)).quantize(Decimal(str(1/10**d)), rounding=ROUND_HALF_UP)
    p = float(p)
    return p

print(my_round(2.675, d=2))

実行結果:

2.68
1
1
1

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
1
1