Courses
在 Python 中将数字四舍五入到小数点后两位是一项重要技巧,尤其适用于财务计算、数据展示和科学报告。
Python 提供了多种精确取整的方法。在本教程中,我将演示如何使用内置函数、库以及格式化方法,将数字保留到小数点后两位。
如果您刚开始做数据分析,建议学习 DataCamp 的Introduction to Python课程,掌握用于数据处理与转换的 Python 基础。如果您需要在数据分析工作流中对大型数值数组进行取整,我们的Python NumPy 教程也会很有帮助。
要点速览
-
算术取整请用
round(number, 2)—— 它会改变实际数值。 -
仅用于显示请用
f"{number:.2f}"或str.format()—— 原始浮点数不变。 -
需要精确小数表示(如金融计算)时使用
decimal模块。 -
用
np.round(array, 2)一次性对整个 NumPy 数组取整。 -
注意浮点精度陷阱:由于浮点在内存中的存储方式,
round(2.675, 2)返回的是2.67,而不是2.68。
理解取整与小数位
小数位是指数字中小数点后出现的位数。小数位决定了数字的精度:小数位越多,数值越精确,反之亦然。
对数字进行取整是指通过减少小数位来调整数字。这一技巧通常用于简化数字并在计算间保持一致性。但将数字取整到特定小数位也会引入微小误差,从而影响计算结果的准确性。
Python 提供了多种方式将数字取整到两位小数。下面的示例对这些技术做了详细说明。
在 Python 中使用 round() 取整
round() 是 Python 的内置函数,用于将浮点数取整到指定的小数位。您可以在第二个参数中给出要保留的小数位数。下面的示例会打印 34.15。
# Example number to be rounded
number = 34.14559
# Rounding the number to 2 decimal places
rounded_number = round(number, 2)
print(rounded_number)
# 34.15
当省略第二个参数时,Python 的 round() 函数使用“就近取偶”(bankers’ rounding)作为默认舍入模式。就近取偶是指当一个数正好位于两个整数的中间时,将其舍入到最接近的偶数整数。该技术有助于减少累计的舍入误差。
round() 的浮点精度小陷阱
在将 round() 用于金融代码前,有个细节值得注意。试试下面的代码:
print(round(2.675, 2)) # You might expect 2.68
# Output: 2.67
结果是 2.67,而不是 2.68。值 2.675 无法在二进制浮点(IEEE 754)中被精确表示;存储的值略小于 2.675,因此 Python 会向下舍入。
如果您在金融计算中需要精确的舍入,请使用带有显式舍入模式的 decimal 模块:
from decimal import Decimal, ROUND_HALF_UP
result = Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
print(result) # 2.68
使用字符串格式化在 Python 中取整
字符串格式化在将数字保留到两位小数时非常实用,尤其适合用于输出展示。
请注意,在 Python 中使用字符串格式化来取整时,显示的结果是字符串,原始数字并未改变。如果随后对原始数字进行计算,仍会基于未取整的值,可能产生意外结果。
使用 % 运算符取整
% 运算符提供了一种传统方式,将数字格式化为两位小数。通过在占位符中插入值可以创建格式化字符串。
在下面的例子中,f 表示按浮点数格式输出,.2 指定保留两位小数。
# Example number to be rounded
number = 3.14159
# Using the % operator to round to 2 decimal places
formatted_number = "%.2f" % number
print(formatted_number)
# 3.14
使用 str.format() 取整
str.format() 方法在处理更复杂的格式化与取整时更灵活。由于支持命名占位符,开发者通常更偏好此方法而非 % 运算符。下面的示例中,在花括号内使用 :.2f 指定将数字保留两位小数。代码将打印 3.14。
# Example number to be rounded
number = 3.14159
# Using str.format() to round to 2 decimal places
formatted_number = "{:.2f}".format(number)
print(formatted_number)
# 3.14
使用 f-string(Python 3.6+)取整
f-string 在 Python 3.6 引入,如今是将值嵌入字符串的首选方式。f-string 语法在取整方面非常简洁:无需单独调用,单行即可完成显示格式化。下面的代码会打印 14.68。
# Example number to be rounded
number = 14.67856
# Using f-strings to round to 2 decimal places
formatted_number = f"{number:.2f}"
print(formatted_number)
# 14.68
使用 format() 在 Python 中取整
内置的 format() 函数接受一个值和格式说明,并返回格式化后的字符串。不同于 str.format(),它直接传入数字,而不是嵌入到模板字符串中。下面的代码会打印 345.69。
# Example number to be rounded
number = 345.68776
# Using the built-in format() to round to 2 decimal places
formatted_number = format(number, ".2f")
print(formatted_number)
# 345.69
使用其他模块在 Python 中取整
除了基础的 Python,还有许多模块可以用于取整。我将展示三个最常用的示例:math、decimal 和 NumPy。
使用 math 模块取整
math 模块并不直接提供按特定小数位取整的函数。不过,您可以结合 math 模块与算术运算,将数字取整到两位小数。
math.floor() 用于将数字向下取整到最接近的整数。若要向下保留两位小数,可先将数字乘以 100,应用 math.floor(),再除以 100。下面的代码会打印 3.14。
# Import math module
import math
# Example number to be rounded
number = 3.14159
# Using math.floor() to round down to 2 decimal places
rounded_down = math.floor(number * 100) / 100
print(rounded_down)
# 3.14
同样地,math.ceil() 会将数字向上取整到最接近的整数。若要向上保留两位小数,可先乘以 100,应用 math.ceil(),再除以 100。下面的代码会打印 3.15。
# Import the math module
import math
# Example number to be rounded
number = 3.14159
# Using math.ceil() to round up to 2 decimal places
rounded_up = math.ceil(number * 100) / 100
print(rounded_up)
# 3.15
使用 decimal 模块取整
Python 的 decimal 模块可通过 .quantize() 方法,将浮点数精确地取整到指定小数位。下面的示例中,我们将精度设为 0.01,表示需要保留两位小数。
# Import the decimal module
from decimal import Decimal
# Example number to be rounded
number = Decimal("18.73869")
# Define the rounding precision to 2 decimal places
precision = Decimal('0.01')
# Using the quantize method with ROUND_UP
# to round the number up to 2 decimal places
rounded_number = number.quantize(precision)
print(rounded_number)
# 18.74
如果您需要特定的“向上取整”行为,欢迎查看我们的最新教程How to Round Up a Number in Python,了解如何使用 math 与 decimal 等方法确保始终向上取整,而不是向下。如果您想更系统地学习数据转换,也可以学习我们的Data Analyst with Python职业路径,提升分析能力。
使用 NumPy 取整
在使用 NumPy 处理数组时,使用 np.round() 可以一次性对所有元素取整。这比手动遍历更快、更清晰。
import numpy as np
prices = np.array([1.2345, 9.8765, 3.14159])
rounded_prices = np.round(prices, 2)
print(rounded_prices)
# [1.23 9.88 3.14]
np.round() 采用与 Python 内置 round() 相同的银行家舍入规则。.round() 方法在 pandas 的 DataFrame 和 Series 上也以相同方式工作:
import pandas as pd
df = pd.DataFrame({"price": [1.2345, 9.8765, 3.14159]})
df["price_rounded"] = df["price"].round(2)
print(df)
# price price_rounded
# 0 1.2345 1.23
# 1 9.8765 9.88
# 2 3.14159 3.14
关于更广泛的数据转换实践,请参阅我们的 pandas 教程。
何时使用哪种 Python 取整方法
以下是选择合适取整方式的速查:
| 方法 | 最适合 | 是否改变值? | 返回类型 |
|---|---|---|---|
round(x, 2) |
通用算术计算 | 是 | float |
f"{x:.2f}" |
展示 / 打印 | 否 | str |
str.format() |
展示 / 打印 | 否 | str |
% operator |
展示 / 打印(旧方式) | 否 | str |
format(x, ".2f") |
展示 / 单个值 | 否 | str |
math.floor() / ceil() |
始终向下 / 向上 | 是 | float |
Decimal.quantize() |
金融 / 精确小数 | 是 | Decimal |
np.round(arr, 2) |
NumPy 数组 | 是 | ndarray |
一些经验法则帮助您选择:
-
只是用于显示数字? 使用 f-string(
f"{x:.2f}")。一行搞定,无需导入,也不会影响原始值。 -
还要对结果继续计算? 使用
round(x, 2)。它返回可继续参与计算的浮点数。 -
金融或会计代码? 使用
Decimal.quantize()。使用decimal模块不会出现浮点精度意外(如round(2.675, 2) == 2.67)。 -
需要始终向上或始终向下? 使用
math.ceil()或math.floor()。它们完全不考虑常规舍入规则。 -
在处理 NumPy 数组或 pandas 列? 使用
np.round(arr, 2)或series.round(2)。两者都能一次处理整个集合。 -
维护旧代码?
%运算符仍然可用,但在 Python 3.6 中已被 f-string 取代——新代码更推荐使用 f-string。
结语
将数字保留到小数点后两位是提升财务与科学计算表达精度的重要技巧。本文介绍了包括内置函数、字符串格式化以及 math 模块在内的多种取整方法。请根据具体需求(如精度与展示格式)选择合适的方法。也建议您通过不同示例多加练习,以便为各自的使用场景找到最合适的做法。
如果您想进一步提升 Python 技能,可以查看我们的Python Programming技能路径,涵盖函数、装饰器与高级 Python 模式。我们的Python Developer职业路径也旨在帮助您作为开发者进阶,学习更高级的数据结构与算法。
常见问题解答
在 Python 中,将数字保留两位小数的最简单方法是什么?
将数字保留两位小数的最简单方法是使用内置的 round() 函数。
为什么使用 round() 函数时数字会被四舍五入到最接近的整数?
round() 的默认方法是“就近取偶”。要将数字保留两位小数,必须在函数中提供第二个参数为 2,例如 round(3.14159, 2)。
如何使用 format() 函数将数字保留两位小数?
format() 函数用于将数字保留到指定的小数位,并在格式化字符串中显示。
什么是就近取偶(round half to even)?
“就近取偶”或银行家舍入,是指当一个数字恰好位于两个整数的中间时,将其舍入到最近的偶数整数。
为什么 round(2.675, 2) 返回 2.67 而不是 2.68?
这是一个浮点精度问题。值 2.675 无法在二进制浮点(IEEE 754)中被精确表示;存储的值略小于 2.675,因此 Python 会向下舍入为 2.67。
在金融代码中为避免此问题,请使用带显式舍入模式的 decimal 模块:Decimal("2.675").quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) 会按预期返回 2.68。
如何将 pandas DataFrame 中的所有值保留两位小数?
对 DataFrame 或 Series 使用 .round() 方法。若只需取整单列:df["price"] = df["price"].round(2)。若要一次性取整所有数值列:df = df.round(2)。
How do I round all values in a pandas DataFrame to 2 decimal places?
Use the .round() method on a DataFrame or Series. To round a single column: df["price"] = df["price"].round(2). To round all numeric columns at once: df = df.round(2).