我想找到解决方法,那就是如何在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.
答案 0 :(得分: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
答案 1 :(得分:2)
您的代码适合我:
$ val=3.45678 NUM=3; printf "%7.${NUM}f\n" "$val"
3.457
$ val=3.45678 NUM=4; printf "%7.${NUM}f\n" "$val"
3.4568
答案 2 :(得分:0)
当然可以做到:
val='15.23456'
NUM=5
printf "%7.${NUM}f\n" "$val"
15.23456
NUM=4
printf "%7.${NUM}f\n" "$val"
15.2346