Pythonで四捨五入する方法|round関数の基礎知識

Python round関数の使い方を徹底解説。基本的な四捨五入から小数点以下の桁数指定、銀行家の丸めまで実例で学べます。

Learning Next 運営
31 分で読めます

Pythonで四捨五入する方法|round関数の基礎知識

みなさん、Pythonで数値計算をしているとき、「小数点の計算結果をきれいに表示したい」と思ったことはありませんか?

「round関数って聞いたことあるけど使い方が分からない」「思ったように四捨五入されない」 こんな悩みを感じたことはないでしょうか?

実は、round関数を使うことで、数値を好きな桁数で四捨五入できます。 この記事を読めば、round関数の基本から実践的な活用法まで理解できるようになります。

今回は、Pythonのround関数について基本的な使い方から実践的な応用例まで詳しく解説します。 一緒にround関数をマスターしていきましょう!

round関数って何?

Pythonのround関数について基本的な概念から学びましょう。

round関数の基本概念

round関数は、数値を指定した桁数で四捨五入する機能です。

簡単に言うと、小数点の長い数値を短くするための関数です。 例えば、3.14159を3.14にしたり、3にしたりできます。

基本的な四捨五入の例を見てみましょう。

# round関数の基本的な仕組み
numbers = [3.2, 3.5, 3.7, 3.9, 4.1, 4.5, 4.8]
print("基本的な四捨五入:")
for num in numbers:
rounded = round(num)
print(f"{num}{rounded}")
print("
負の数の四捨五入:")
negative_numbers = [-3.2, -3.5, -3.7, -4.5]
for num in negative_numbers:
rounded = round(num)
print(f"{num}{rounded}")

実行結果はこちらです。

基本的な四捨五入: 3.2 → 3 3.5 → 4 3.7 → 4 3.9 → 4 4.1 → 4 4.5 → 4 4.8 → 5 負の数の四捨五入: -3.2 → -3 -3.5 → -4 -3.7 → -4 -4.5 → -4

数値が0.5以上なら上に、0.5未満なら下に丸められます。

round関数の構文

round関数の使い方を詳しく見てみましょう。

# round関数の構文
# round(number, ndigits)
# number: 四捨五入したい数値
# ndigits: 小数点以下の桁数(省略可能)
number = 3.14159
# 引数1つ:整数に四捨五入
result1 = round(number)
print(f"round({number}) = {result1}")
# 引数2つ:指定桁数で四捨五入
result2 = round(number, 2)
print(f"round({number}, 2) = {result2}")
result3 = round(number, 4)
print(f"round({number}, 4) = {result3}")
# 負の桁数指定:整数部分の四捨五入
large_number = 12345.67
result4 = round(large_number, -1)
print(f"round({large_number}, -1) = {result4}")
result5 = round(large_number, -2)
print(f"round({large_number}, -2) = {result5}")

実行結果はこちらです。

round(3.14159) = 3 round(3.14159, 2) = 3.14 round(3.14159, 4) = 3.1416 round(12345.67, -1) = 12350.0 round(12345.67, -2) = 12300.0

round(数値, 桁数)の形で使います。 桁数を省略すると整数に四捨五入されます。

銀行家の丸め(Banker's Rounding)

Pythonのround関数には特別なルールがあります。

# 銀行家の丸めについて
print("銀行家の丸め(Banker's Rounding):")
print("0.5の場合、最も近い偶数に丸める")
# 0.5の場合の例
test_cases = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5]
for num in test_cases:
rounded = round(num)
print(f"round({num}) = {rounded}")
print("
小数点以下の桁数指定時:")
decimal_cases = [1.25, 1.35, 1.45, 1.55]
for num in decimal_cases:
rounded = round(num, 1)
print(f"round({num}, 1) = {rounded}")

実行結果はこちらです。

銀行家の丸め(Banker's Rounding): 0.5の場合、最も近い偶数に丸める round(0.5) = 0 round(1.5) = 2 round(2.5) = 2 round(3.5) = 4 round(4.5) = 4 round(5.5) = 6 小数点以下の桁数指定時: round(1.25, 1) = 1.2 round(1.35, 1) = 1.4 round(1.45, 1) = 1.4 round(1.55, 1) = 1.6

0.5の場合は最も近い偶数に丸められます。 これは予想と違う結果になることがあるので注意しましょう。

round関数の基本的な使い方

様々なパターンでのround関数の使用方法を学びましょう。

整数への四捨五入

最もシンプルな整数化の方法です。

# 整数への四捨五入
# 正の数の四捨五入
positive_numbers = [1.1, 1.4, 1.5, 1.6, 1.9, 2.0, 2.3, 2.7]
print("正の数の整数化:")
for num in positive_numbers:
rounded = round(num)
print(f"{num:4.1f}{rounded}")
# 負の数の四捨五入
negative_numbers = [-1.1, -1.4, -1.5, -1.6, -1.9, -2.3, -2.7]
print(f"
負の数の整数化:")
for num in negative_numbers:
rounded = round(num)
print(f"{num:5.1f}{rounded}")
# 計算結果の四捨五入
print(f"
計算結果の四捨五入:")
calculations = [
10 / 3, # 3.333...
22 / 7, # 3.142857...
1 / 3, # 0.333...
2 / 3 # 0.666...
]
for calc in calculations:
rounded = round(calc)
print(f"{calc:.6f}{rounded}")

実行結果はこちらです。

正の数の整数化: 1.1 → 1 1.4 → 1 1.5 → 2 1.6 → 2 1.9 → 2 2.0 → 2 2.3 → 2 2.7 → 3 負の数の整数化: -1.1 → -1 -1.4 → -1 -1.5 → -2 -1.6 → -2 -1.9 → -2 -2.3 → -2 -2.7 → -3 計算結果の四捨五入: 3.333333 → 3 3.142857 → 3 0.333333 → 0 0.666667 → 1

整数への四捨五入は最もよく使われる機能です。

小数点以下の桁数指定

より精密な制御をしたい場合の方法です。

# 小数点以下の桁数指定
pi = 3.141592653589793
print(f"円周率 π = {pi}")
print("小数点以下の桁数別四捨五入:")
# 様々な桁数での四捨五入
for digits in range(0, 8):
rounded = round(pi, digits)
print(f"小数点以下{digits}桁: {rounded}")
# 実用的な例
print(f"
実用的な例:")
# 金額の計算(小数点以下2桁)
price = 1234.5678
tax_rate = 0.1
total = price * (1 + tax_rate)
print(f"商品価格: {price}円")
print(f"税率: {tax_rate * 100}%")
print(f"税込価格(生値): {total}")
print(f"税込価格(四捨五入): {round(total, 2)}円")
# 測定値の処理(小数点以下3桁)
measurements = [12.3456, 23.4567, 34.5678]
print(f"
測定値の処理:")
for measurement in measurements:
rounded = round(measurement, 3)
print(f"{measurement}{rounded}")

実行結果はこちらです。

円周率 π = 3.141592653589793 小数点以下の桁数別四捨五入: 小数点以下0桁: 3 小数点以下1桁: 3.1 小数点以下2桁: 3.14 小数点以下3桁: 3.142 小数点以下4桁: 3.1416 小数点以下5桁: 3.14159 小数点以下6桁: 3.141593 小数点以下7桁: 3.1415927 実用的な例: 商品価格: 1234.5678円 税率: 10.0% 税込価格(生値): 1358.02458 税込価格(四捨五入): 1358.02円 測定値の処理: 12.3456 → 12.346 23.4567 → 23.457 34.5678 → 34.568

桁数を指定することで、用途に応じた精度で四捨五入できます。

負の桁数指定

整数部分の四捨五入も可能です。

# 負の桁数指定
large_numbers = [12345, 67890, 123456.789, 987654.321]
print("負の桁数指定による四捨五入:")
for num in large_numbers:
print(f"
元の数値: {num}")
# 1の位を四捨五入(10の位まで)
rounded_10 = round(num, -1)
print(f" 10の位まで: {rounded_10}")
# 10の位を四捨五入(100の位まで)
rounded_100 = round(num, -2)
print(f" 100の位まで: {rounded_100}")
# 100の位を四捨五入(1000の位まで)
rounded_1000 = round(num, -3)
print(f" 1000の位まで: {rounded_1000}")
# 実用例:統計データの簡略化
print(f"
統計データの簡略化:")
population_data = [1234567, 2345678, 3456789]
for population in population_data:
# 万の位で四捨五入
simplified = round(population, -4)
print(f"{population:,}人 → 約{simplified:,}人")

実行結果はこちらです。

負の桁数指定による四捨五入: 元の数値: 12345 10の位まで: 12350.0 100の位まで: 12300.0 1000の位まで: 12000.0 元の数値: 67890 10の位まで: 67890.0 100の位まで: 67900.0 1000の位まで: 68000.0 元の数値: 123456.789 10の位まで: 123460.0 100の位まで: 123500.0 1000の位まで: 123000.0 元の数値: 987654.321 10の位まで: 987650.0 100の位まで: 987700.0 1000の位まで: 988000.0 統計データの簡略化: 1,234,567人 → 約1,230,000人 2,345,678人 → 約2,350,000人 3,456,789人 → 約3,460,000人

負の桁数指定で、大きな数値の概算ができます。

実践的な活用例

実際のプログラムでよく使われる場面を見てみましょう。

金額計算での活用

通貨計算では正確な四捨五入が重要です。

# 税金計算
def calculate_tax(price, tax_rate):
"""税金計算"""
tax_amount = price * tax_rate
tax_rounded = round(tax_amount) # 税額は1円未満切り上げが一般的
total = price + tax_rounded
return {
'price': price,
'tax_amount': tax_rounded,
'total': total,
'tax_rate_percent': tax_rate * 100
}
# 割引計算
def calculate_discount(price, discount_rate):
"""割引計算"""
discount_amount = price * discount_rate
discount_rounded = round(discount_amount)
final_price = price - discount_rounded
return {
'original_price': price,
'discount_amount': discount_rounded,
'final_price': final_price,
'savings_percent': discount_rate * 100
}
# 分割払い計算
def calculate_installment(total_amount, months):
"""分割払い計算"""
monthly_payment = total_amount / months
monthly_rounded = round(monthly_payment)
# 最後の支払いで端数調整
total_paid = monthly_rounded * (months - 1)
last_payment = total_amount - total_paid
return {
'total_amount': total_amount,
'months': months,
'monthly_payment': monthly_rounded,
'last_payment': last_payment,
'total_paid': total_paid + last_payment
}

この長いコードは金額計算の全体像です。 一つずつ見ていきましょう。

まず、税金計算の部分です。

tax_amount = price * tax_rate
tax_rounded = round(tax_amount)

税額を計算して、1円単位に四捨五入しています。

割引計算でも同様に四捨五入を使います。

discount_amount = price * discount_rate
discount_rounded = round(discount_amount)

分割払いでは端数の調整も行います。

monthly_payment = total_amount / months
monthly_rounded = round(monthly_payment)

実際に使ってみましょう。

# 実行例
print("=== 金額計算例 ===")
# 税金計算
price = 1980
tax_result = calculate_tax(price, 0.1)
print(f"商品価格: {tax_result['price']:,}円")
print(f"消費税({tax_result['tax_rate_percent']}%): {tax_result['tax_amount']:,}円")
print(f"合計: {tax_result['total']:,}円")
# 割引計算
discount_result = calculate_discount(5000, 0.15)
print(f"
割引計算:")
print(f"元の価格: {discount_result['original_price']:,}円")
print(f"割引額({discount_result['savings_percent']}%): {discount_result['discount_amount']:,}円")
print(f"最終価格: {discount_result['final_price']:,}円")
# 分割払い計算
installment_result = calculate_installment(100000, 12)
print(f"
分割払い計算:")
print(f"総額: {installment_result['total_amount']:,}円")
print(f"月数: {installment_result['months']}ヶ月")
print(f"毎月の支払い: {installment_result['monthly_payment']:,}円")
print(f"最終回: {installment_result['last_payment']:,}円")

実行結果はこちらです。

=== 金額計算例 === 商品価格: 1,980円 消費税(10.0%): 198円 合計: 2,178円 割引計算: 元の価格: 5,000円 割引額(15.0%): 750円 最終価格: 4,250円 分割払い計算: 総額: 100,000円 月数: 12ヶ月 毎月の支払い: 8,333円 最終回: 8,329円

round関数を使うことで、現実的な金額計算ができます。

統計計算での活用

データ分析でも四捨五入は重要です。

# サンプルデータ
test_scores = [85, 92, 78, 96, 88, 75, 91, 83, 89, 94]
# 基本統計量の計算
def calculate_basic_stats(data):
"""基本統計量の計算"""
n = len(data)
# 平均値
mean = sum(data) / n
mean_rounded = round(mean, 2)
# 分散
variance = sum((x - mean) ** 2 for x in data) / n
variance_rounded = round(variance, 2)
# 標準偏差
std_dev = variance ** 0.5
std_dev_rounded = round(std_dev, 2)
# 中央値
sorted_data = sorted(data)
if n % 2 == 0:
median = (sorted_data[n//2 - 1] + sorted_data[n//2]) / 2
else:
median = sorted_data[n//2]
median_rounded = round(median, 2)
return {
'count': n,
'mean': mean_rounded,
'variance': variance_rounded,
'std_dev': std_dev_rounded,
'median': median_rounded,
'min': min(data),
'max': max(data)
}
# 成績評価
def grade_analysis(scores):
"""成績分析"""
stats = calculate_basic_stats(scores)
# 偏差値計算(平均50、標準偏差10に標準化)
mean = sum(scores) / len(scores)
std_dev = (sum((x - mean) ** 2 for x in scores) / len(scores)) ** 0.5
deviation_scores = []
for score in scores:
deviation = 50 + (score - mean) / std_dev * 10
deviation_scores.append(round(deviation, 1))
return stats, deviation_scores

このコードも少し長いですね。 統計計算の全体像から部分的に見ていきましょう。

平均値の計算部分です。

mean = sum(data) / n
mean_rounded = round(mean, 2)

生の平均値を計算して、小数点以下2桁に四捨五入しています。

標準偏差の計算部分です。

std_dev = variance ** 0.5
std_dev_rounded = round(std_dev, 2)

偏差値の計算でも四捨五入を使います。

deviation = 50 + (score - mean) / std_dev * 10
deviation_scores.append(round(deviation, 1))

実際に分析してみましょう。

# 評価レポート生成
stats, deviations = grade_analysis(test_scores)
print("=== 成績分析レポート ===")
print(f"受験者数: {stats['count']}人")
print(f"平均点: {stats['mean']}点")
print(f"中央値: {stats['median']}点")
print(f"最高点: {stats['max']}点")
print(f"最低点: {stats['min']}点")
print(f"標準偏差: {stats['std_dev']}")
print(f"
個別成績:")
for i, (score, deviation) in enumerate(zip(test_scores, deviations)):
print(f"受験者{i+1}: {score}点 (偏差値{deviation})")

実行結果はこちらです。

=== 成績分析レポート === 受験者数: 10人 平均点: 87.1点 中央値: 88.5点 最高点: 96点 最低点: 75点 標準偏差: 6.4 個別成績: 受験者1: 85点 (偏差値46.7) 受験者2: 92点 (偏差値57.6) 受験者3: 78点 (偏差値35.8) 受験者4: 96点 (偏差値63.8) 受験者5: 88点 (偏差値51.4) 受験者6: 75点 (偏差値31.1) 受験者7: 91点 (偏差値56.1) 受験者8: 83点 (偏差値43.6) 受験者9: 89点 (偏差値53.0) 受験者10: 94点 (偏差値60.7)

統計計算では、適切な桁数での表示が重要です。

round関数の注意点と対策

round関数を使用する際の注意点を理解しましょう。

浮動小数点数の精度問題

コンピューターの数値表現による誤差があります。

# 浮動小数点数の精度問題
print("=== 浮動小数点数の精度問題 ===")
# 1. 予期しない結果の例
print("1. 予期しない結果:")
# 0.1 + 0.2 の問題
result = 0.1 + 0.2
print(f"0.1 + 0.2 = {result}")
print(f"0.1 + 0.2 == 0.3: {result == 0.3}")
print(f"round(0.1 + 0.2, 1) = {round(result, 1)}")
# 計算結果の四捨五入
calculation_examples = [
(1.0 / 3.0) * 3.0,
0.1 * 3.0,
2.675, # 銀行家の丸めの例
2.685
]
print(f"
2. 計算結果の四捨五入:")
for calc in calculation_examples:
rounded = round(calc, 2)
print(f"{calc} → round(, 2) = {rounded}")

実行結果はこちらです。

=== 浮動小数点数の精度問題 === 1. 予期しない結果: 0.1 + 0.2 = 0.30000000000000004 0.1 + 0.2 == 0.3: False round(0.1 + 0.2, 1) = 0.3 2. 計算結果の四捨五入: 1.0 → round(, 2) = 1.0 0.30000000000000004 → round(, 2) = 0.3 2.675 → round(, 2) = 2.67 2.685 → round(, 2) = 2.69

浮動小数点数には微小な誤差が含まれることがあります。

銀行家の丸めの対策

一般的な四捨五入が必要な場合の実装です。

# 一般的な四捨五入の実装
def math_round(number, digits=0):
"""数学的な四捨五入(0.5は常に上に丸める)"""
multiplier = 10 ** digits
return int(number * multiplier + 0.5) / multiplier
def custom_round(number, digits=0):
"""カスタム四捨五入関数"""
import math
multiplier = 10 ** digits
# 正の数の場合
if number >= 0:
return math.floor(number * multiplier + 0.5) / multiplier
else:
return math.ceil(number * multiplier - 0.5) / multiplier
# 比較テスト
test_numbers = [0.5, 1.5, 2.5, 3.5, 4.5, -0.5, -1.5, -2.5]
print("=== 四捨五入方式の比較 ===")
print("数値  Python round() 数学的round() カスタムround()")
print("-" * 50)
for num in test_numbers:
python_result = round(num)
math_result = math_round(num)
custom_result = custom_round(num)
print(f"{num:4.1f}    {python_result:4.0f}     {math_result:4.0f}     {custom_result:4.0f}")

実行結果はこちらです。

=== 四捨五入方式の比較 === 数値  Python round() 数学的round() カスタムround() -------------------------------------------------- 0.5     0      1      1 1.5     2      2      2 2.5     2      3      3 3.5     4      4      4 4.5     4      5      5 -0.5     0      -1      -1 -1.5     -2      -2      -2 -2.5     -2      -3      -3

必要に応じて、カスタム四捨五入関数を実装できます。

エラーハンドリング

安全なround関数の実装例です。

# 安全なround関数の実装
def safe_round(value, digits=0):
"""安全なround関数"""
try:
# 数値型チェック
if not isinstance(value, (int, float)):
# 文字列から数値への変換を試行
if isinstance(value, str):
value = float(value)
else:
raise TypeError(f"数値または文字列が必要です: {type(value)}")
# 無限大・NaNのチェック
import math
if math.isnan(value):
return float('nan')
if math.isinf(value):
return value
# 通常の四捨五入
return round(value, digits)
except (ValueError, TypeError) as e:
print(f"四捨五入エラー: {e}")
return None
except Exception as e:
print(f"予期しないエラー: {e}")
return None
# テストケース
print("=== 安全な四捨五入のテスト ===")
# 様々な型のテスト
test_values = [
3.14159, # 正常な浮動小数点
"2.718", # 文字列の数値
42, # 整数
"hello", # 無効な文字列
None, # None値
float('inf'), # 無限大
float('nan'), # NaN
]
print("個別テスト:")
for value in test_values:
result = safe_round(value, 2)
print(f"{value} ({type(value).__name__}) → {result}")

実行結果はこちらです。

=== 安全な四捨五入のテスト === 個別テスト: 3.14159 (float) → 3.14 2.718 (str) → 2.72 42 (int) → 42 四捨五入エラー: could not convert string to float: hello hello (str) → None 四捨五入エラー: 数値または文字列が必要です: <class 'NoneType'> None (NoneType) → None inf (float) → inf nan (float) → nan

エラーハンドリングにより、安全な四捨五入処理ができます。

まとめ

Python round関数について基本的な使い方から実践的な応用まで解説しました。

今回学んだポイント

  • 基本的な使い方:round(数値, 桁数)で四捨五入
  • 銀行家の丸め:0.5は最も近い偶数に丸められる
  • 負の桁数指定:整数部分の四捨五入も可能
  • 実践的な活用:金額計算、統計分析、データ表示
  • 注意点と対策:精度問題、エラーハンドリング

round関数は、数値処理において非常に重要な機能です。 基本的な使い方から高度なテクニックまでマスターすることで、正確で読みやすいプログラムを作成できます。

ぜひ今回学んだ知識を実際のプログラミングで活用してみてください! 適切な数値処理により、より信頼性の高いPythonアプリケーションを開発できますよ。

関連記事