在 Python 中,你可以使用字符串的 format
方法或 f-string(Python 3.6 及以上版本)来格式化输出百分比并控制精度。以下是两种方法的示例:
format
方法percentage = 0.12345
# 使用 format 方法格式化输出百分比,并控制精度为2位小数
formatted_percentage = "{:.2%}".format(percentage)
print(formatted_percentage) # 输出: 12.35%
percentage = 0.12345
# 使用 f-string 格式化输出百分比,并控制精度为2位小数
formatted_percentage = f"{percentage:.2%}"
print(formatted_percentage) # 输出: 12.35%
:.2%
是格式化字符串的一部分:
:
表示格式化的开始。.2
表示保留两位小数。%
表示将小数转换为百分比形式(即乘以 100 并添加百分号)。如果你想要保留 1 位小数:
formatted_percentage = "{:.1%}".format(percentage)
print(formatted_percentage) # 输出: 12.3%
如果你想要保留 3 位小数:
formatted_percentage = "{:.3%}".format(percentage)
print(formatted_percentage) # 输出: 12.345%
通过这种方式,你可以灵活地控制百分比输出的精度。