Python 浮点数小数点位数控制方法
在Python中,可以使用round函数来控制浮点数的小数点位数。round函数的第二个参数可以指定小数点后的位数。例如:
a = 3.14159
print(round(a, 2)) # 输出:3.14
b = 2.71828
print(round(b, 3)) # 输出:2.718
另外,如果希望直接打印出指定小数点位数的浮点数,可以使用字符串的格式化功能。例如:
a = 3.14159
print('{:.2f}'.format(a)) # 输出:3.14
b = 2.71828
print('{:.3f}'.format(b)) # 输出:2.718
这样可以将浮点数格式化为指定的小数点位数,并直接输出。
原文地址: https://www.cveoy.top/t/topic/fXXh 著作权归作者所有。请勿转载和采集!