python正确保留一位小数的方法

python正确保留一位小数的方法(可扩展至多位)

方法1:用round函数

a=12.34567889
round(a,1)=12.3
#保留一位小数

round(a,2)=12.35
#保留二位小数

方法2:格式化输入

a=12.34567889
print(“%.1f”%a)
#保留一位小数

print(“%.3f”%a)
#保留三位小数

print(“%.4f”%a)
#保留四位小数

方法3:引入decimal函数

from decimal import Decimal
a=134.5657768
t=Decimal(“134.5657768”).quantize(Decimal(“0.0”))
print(t)
#输出结果:1134.5

学习笔记
不完全,待补充
参考于在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_53052839/article/details/110308199