是否可以传递一个变量来控制printf中的精度?

Dan*_*iel 0 bash shell printf

我想找到解决这个问题的方法,那就是如何在printf中将变量作为精度控制传递?

printf "%7.5f\n" "$val" --> This is OKAY, I know
printf "%7.${NUM}f\n" "$val" --> Where NUM could be 2,3,4, or 5, etc.
Run Code Online (Sandbox Code Playgroud)

ric*_*ici 5

更简洁的方法是使用*修饰符,就像在C中一样.

$ for i in {0..5}; do
>   printf "%7.*f\n" $i 3.14159265358979323844
> done
      3
    3.1
   3.14
  3.142
 3.1416
3.14159
Run Code Online (Sandbox Code Playgroud)