zl程序教程

您现在的位置是:首页 >  Python

当前栏目

python如何控制打印几位小数?

2023-03-20 14:45:39 时间

python如何控制打印几位小数?

方法一:round(X, N)

该方法并不严格有效,当X小数位数n<N时,仅能够输出n位小数。

方法二:print('%.Nf'%X)或者print("%.Nf"%X)

注意该方法有两个“%”,没有“,”。

方法三:print(format(X, '.Nf')或者print(format(X,".Nf")

注意该方法没有"%",但有“,”。

X可以为计算表达式!

print(round(2,2))             #2
print(round(2.0,2))           #2.0
print(round(2.00,2))          #2.0
print('%.2f'%10)              #10.00
print(format(10,'.2f'))       #10.00