python - How to print a given number of decimal places?
问题描述
I want to print my result with a specific number of decimal places inside of a for loop where the value of it is the number of decimal places to be printed.
Below is a sample of the relevant part of the code:
for i in range (-15, -7):
print ('Valor do erro:' , 10**i, 'Valor da serie:', count, '------->', '%.16f' % adder(count))
解决方案
格式说明符可以嵌套:
>>> for i in range(1, 5):
... print("{:.{}f}".format(1/i, i))
...
1.0
0.50
0.333
0.2500
在这里,1/i
转到第一个(外部){...}
和i
第二个(内部){}
。
但请注意,小数位数不能为负数。为此,您可能只想使用科学记数法。
>>> for i in range(-2, 3):
... print("{:.2e}".format(10**i))
...
1.00e-02
1.00e-01
1.00e+00
1.00e+01
1.00e+02
推荐阅读
- java - Android WallpaperManager 方法“软砖化”用户的手机并导致设备无响应
- laravel-5.1 - 有什么方法可以绕过 Laravel 上的 Model::created() 事件吗?
- bash - 阻止失败的假脱机创建文件?
- qemu - 错误:不存在 DTC (libfdt) 版本 >= 1.4.2。请安装 DTC (libfdt) 开发包
- c# - 来自 Nike.com 的 Web 请求响应被禁止
- javascript - 我如何从 Rails 视图中获取ElementById
- python - ValueError:只能比较标记相同的系列对象 | 比较数据框中的值
- css - 是否可以在通用过渡 Stylus mixin 中创建滚动?
- processing - 意外令牌:处理中的 int
- hadoop - 为每个赛季寻找得分最高的主队