将浮点数限制为两位小数

将浮点数限制为两位小数

技术背景

在Python中处理浮点数时,会遇到一个常见问题:并非所有数字都能被精确表示。这是因为计算机采用二进制存储浮点数,会将其存储为整数再除以2的幂。例如,13.95在计算机中可能会被表示为类似125650429603636838/(2**53)的形式。双精度数有53位(16位数字)的精度,普通浮点数有24位(8位数字)的精度,Python中的浮点数类型使用双精度来存储值。

实现步骤

方法一:使用字符串格式化

1
2
3
4
5
6
7
8
a = 13.949999999999999
# 输出为字符串
formatted_str = "{:.2f}".format(a)
print(formatted_str)

# 若需要转换为浮点数
formatted_float = float("{:.2f}".format(a))
print(formatted_float)

方法二:使用round()函数

1
2
3
a = 13.949999999999999
rounded_num = round(a, 2)
print(rounded_num)

方法三:使用旧的字符串格式化方式(Python 2)

1
2
3
a = 13.949999999999999
formatted_str = "%.2f" % a
print(formatted_str)

方法四:使用f-string(Python 3.6+)

1
2
3
a = 13.949999999999999
f_str = f'{a:.2f}'
print(f_str)

方法五:使用decimal模块

1
2
3
4
from decimal import Decimal
d1 = Decimal(13.949999999999999)
d2 = round(d1, 2)
print(d2)

核心代码

限制浮点数为两位小数的通用代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 字符串格式化
def format_float_to_str(num):
return "{:.2f}".format(num)

# 使用round函数
def round_float(num):
return round(num, 2)

# f-string方式
def f_string_format(num):
return f'{num:.2f}'

# decimal模块方式
from decimal import Decimal
def decimal_round(num):
d = Decimal(num)
return round(d, 2)

# 测试
num = 13.949999999999999
print(format_float_to_str(num))
print(round_float(num))
print(f_string_format(num))
print(decimal_round(num))

最佳实践

  • 如果只是为了显示特定精度的浮点数,如显示货币值,推荐使用字符串格式化方法,如"{:.2f}".format()或f-string。
  • 如果需要进行数学计算并保持精度,建议使用decimal模块。
  • 在Python 3.6及以上版本,优先使用f-string,代码更简洁易读。

常见问题

浮点数表示不准确

由于浮点数的二进制表示,某些十进制数无法精确表示。例如,0.1在计算机中存储为近似值,这可能导致计算结果出现微小误差。可以使用decimal模块来解决这个问题。

不同版本Python的兼容性问题

  • 在Python 2中,可以使用"%.2f" % num"{:.2f}".format(num)两种方式,但在Python 3中,推荐使用"{:.2f}".format(num)或f-string。
  • 对于旧版本Python,可能需要考虑round()函数的行为差异。在Python 3.1及Python 2.7.0之后,浮点数和字符串之间的转换会正确舍入。

将浮点数限制为两位小数
https://119291.xyz/posts/2025-05-15.limiting-floats-to-two-decimal-points/
作者
ww
发布于
2025年5月15日
许可协议