在Python中,可以使用几种方法来保留小数的位数:
使用字符串的
format()
方法或格式化字符串字面量(f-string)。使用
round()
函数。
使用format()
方法或f-string
# 示例数字
number = 3.141592653589793
# 使用 format() 方法保留两位小数
formatted_number = format(number, '.2f')
print(formatted_number) # 输出: 3.14
# 使用 f-string 保留两位小数
formatted_number_fstring = f"{number:.2f}"
print(formatted_number_fstring) # 输出: 3.14
使用round()
函数
# 示例数字
number = 3.141592653589793
# 使用 round() 函数保留两位小数
rounded_number = round(number, 2)
print(rounded_number) # 输出: 3.14