list保留小数位数

版权声明:提倡知识共享,可以转载和使用 https://blog.csdn.net/Mr_Cat123/article/details/82856908

将下面的list保留4位小数输出

a = [0.00256,0.00265,0.00254,0.00258]

1,输出之后是浮点数

a = [0.00256,0.00265,0.00254,0.00258]
b = [round(i,4) for i in a]

>>> b
0.0026
0.0027
0.0025
0.0026

值得注意的是round函数有时候结果并不像我们想的那样,比如下面的计算
data是一个数据数组,其中第一行第4列为0.0086809999999999995

在这里插入图片描述
上面的结果表明还是使用float(’%.4f’%data[0,3])靠谱。

2,输出之后是字符串
除了使用上面的%.3f%data这种方法外还可以用.format形式

a = [0.00256,0.00265,0.00254,0.00258]
c = ['{:.4f}'.format(i) for i in a] 

Out: ['0.0026', '0.0027', '0.0025', '0.0026']

猜你喜欢

转载自blog.csdn.net/Mr_Cat123/article/details/82856908