0

I want to find a way around this, that is how to pass variable as precision control in 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.
5
  • 3
    You can also use the * modifier, just like in C. printf "%7.*f\n" $NUM $val
    – rici
    Jun 13, 2014 at 20:14
  • @rici Is this syntax correct then? printf "%*.*f\n" $NUM1 $NUM2 $val, if I want to change both 7 and 5?
    – Daniel
    Jun 13, 2014 at 21:02
  • @Daniel Yes, that's correct.
    – chepner
    Jun 13, 2014 at 21:16
  • 1
    @daniel: sure. The * are replaced with arguments in order.
    – rici
    Jun 13, 2014 at 21:16
  • @chepner: OK, answer provided. FWIW.
    – rici
    Jun 13, 2014 at 21:21

3 Answers 3

5

A cleaner way to do it is to use the * modifier, just like in 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
  • Great! Thank you. I found this is a better solution as it can handle awk situation. For example: num=3.1415926; prec=5; echo $num | awk -v vNum=$num -v vPrec=$prec '{ printf "%.*f\n", vPrec, vNum }'
    – Daniel
    Jun 13, 2014 at 21:23
2

Your code works for me:

$ 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
0
0

Sure it can be done:

val='15.23456'

NUM=5
printf "%7.${NUM}f\n" "$val"
15.23456

NUM=4
printf "%7.${NUM}f\n" "$val"
15.2346

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.