Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

padding zero on floating point bash printf

I would like to have a floating point number printed in bash with padded zeroes to fill a range %5.3f. I know of printf function.

My problem is the following:

printf "0%5.3f\n" 3.00

returns, as expected,

03.000

but the line

printf "0%5.3f\n" 23.00

gives instead

023.000 

which is not what I want of course.

Any suggestion?

like image 482
lev.tuby Avatar asked Jan 28 '13 15:01

lev.tuby


2 Answers

You have to put the 0 after the %:

printf "%06.3f\n" 23.00

Notice that I also increased the minimum field width to 6, otherwise no padding will occur (3 decimal places, one dot, leaves just a single digit in front of the decimal point).

like image 75
Michael Wild Avatar answered Nov 11 '22 13:11

Michael Wild


If anything at all, the 0 would have to be on the right side of the percent sign. I don't have a linux system at work, but try printf "%05.3f\n" 23.00.

like image 25
Axel Avatar answered Nov 11 '22 13:11

Axel