Python で数値を丸める際によく使用される round() 関数について、基本的な使い方から実践的な例まで詳しく解説します。

round()関数の基本的な使い方

round() 関数は、数値を指定した小数点以下の桁数で丸めることができます。基本的な構文は以下の通りです:

round(数値, 小数点以下の桁数)

小数点以下の桁数を指定しない場合は、最も近い整数に丸められます。

基本的な使用例

# 整数への丸め
print(round(3.14))  # 出力: 3
print(round(3.7))   # 出力: 4

# 小数点以下の指定桁数での丸め
print(round(3.14159, 2))  # 出力: 3.14
print(round(3.14159, 3))  # 出力: 3.142

注意すべき動作

round() 関数には、いくつか注意すべき特徴があります:

1. 偶数への丸め

数値が中間点(.5)にある場合、最も近い偶数に丸められます:

print(round(2.5))  # 出力: 2
print(round(3.5))  # 出力: 4

2. 浮動小数点数の精度

浮動小数点数の計算における精度の制限により、予期しない結果が生じる場合があります:

print(round(2.675, 2))  # 期待: 2.68, 実際: 2.67

実践的な使用例

金額計算での利用

price = 1234.5678
rounded_price = round(price, 2)
print(f"金額: ¥{rounded_price}")  # 出力: 金額: ¥1234.57

リスト内の数値の一括丸め

numbers = [3.14159, 2.71828, 1.41421]
rounded_numbers = [round(x, 2) for x in numbers]
print(rounded_numbers)  # 出力: [3.14, 2.72, 1.41]

代替手段

より細かい制御が必要な場合は、以下の方法も検討できます:

math.floor() と math.ceil()

import math

# 切り捨て
print(math.floor(3.7))  # 出力: 3

# 切り上げ
print(math.ceil(3.2))   # 出力: 4

format() 関数による文字列フォーマット

number = 3.14159
formatted = "{:.2f}".format(number)
print(formatted)  # 出力: 3.14

まとめ

round() 関数は、Pythonで数値を丸める際の標準的な方法です。基本的な使用は簡単ですが、偶数への丸めや浮動小数点数の精度に関する特徴を理解しておくことが重要です。用途に応じて、math モジュールの関数や文字列フォーマットなどの代替手段も検討してください。