3

I am trying to print 99.11111 as 099.11 in AWK.

I have tried the following variations without success.

$ awk '{printf ("%000.2f\n", $1);}' <<< 99.111111
99.11
$ awk '{printf ("%3.2f\n", $1);}' <<< 99.111111
99.11
$ awk '{printf ("%03.2f\n", $1);}' <<< 99.111111
99.11
0

1 Answer 1

7

Using any awk:

$ awk '{printf("%06.2f\n", $1)}' <<< 99.111111
099.11

The padding length takes into account the whole formatted number, so with the fractional part taking up 3 characters (. and the 2 precision digits), you need a padding length of 6 if you want the integral part to be padded to a length of 3. Note that the padding also takes into account the sign if any so -1 for instance would be formatted as -01.00¹


¹ or possibly -01,00 or -01٫00 depending on the user's locale and the awk implementation². In the case of GNU awk, it also depends on whether there's a POSIXLY_CORRECT variable in the environment or not.

2
  • Without awk: LANG=C printf "%06.2f\n" 99.111111 Commented Feb 26, 2023 at 11:36
  • 1
    @GillesQuénot :I'd just add the warning that, in bash, an integer value (or real when cast to integer) starting with 0 is considered an octal by bash: f() { echo $(( i + 1 )) ;}, then f 003 shows 4, f 003.12 rightly complains about the ".12" part, but f 008complains that 008 doesn't fit the base (base8 as 008 starts with a 0), and f 008.12 also complains about that (before it could complain about the 0.12 part). Additionnaly: f 003 give 4 without surprise but f 011 gives 10, as 011 octal is 9. Commented Feb 27, 2023 at 13:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .