|
|
|
Overview > Misc > Formatting float number output in bash |
Formatting float number output in bashUh, really exciting.... However, sometimes you need to run over some values in bash, send them as float values to a program, and nicely prefix them with zeros so that the resulting string can be used as part of a text file name. First guess was using bc, e.g.
$a=`echo 1/100|bc -l`
However, bc does not give you any way to format the resulting number. As usual it is awk that comes to the rescue: with it's C-like format specifiers for printf. Let's say you have an integer a from a loop, then you do alpha=`echo "$a/100" | bc -l | awk '{printf("%06.2f", $1);}'` to get values in the form "000.01".
Note that the initial number (6 here) indicates the overall number of digits. (2010-05-20, edited 2010-05-21, forgot bc!)
|
|
|
|
|