Skip to content
Advertisement

bash printf not working – decimals [closed]

Why did printf didn’t WORK for the final command printf "%s,%.2fn" "$s","$a" and what’s that extra 0.00 coming from?

When I ran them individually, they worked as expected but not in the final command.

$ s="giga,fifa"; a="8309.18694444444444444444"; echo "$s"; printf "%sn" "$s"; echo -e "n";  echo "$a"; printf "%.2fn" "$a"; echo -e "n"; echo "$s,$a"; printf "%s" "$s,"; printf "%.2fn" "$a";echo;printf "%s,%.2fn" "$s","$a"
giga,fifa
giga,fifa


8309.18694444444444444444
8309.19


giga,fifa,8309.18694444444444444444
giga,fifa,8309.19

giga,fifa,8309.18694444444444444444,0.00

How can I get this output: giga,fifa,8309.19 with just one printf command showing both variables?

Advertisement

Answer

You don’t use a , in bash printf, you delimit with space. The 0.00 comes from trying to parse the "$s","$a" at once, and has odd results – everything is considered one argument and printed as the first string, so no argument exists for the second and a 0 is substituted as default. This works as expected:

>printf "%s,%.2fn" "$s" "$a"
giga,fifa,8309.19
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement