34

I need to printf a number out, but with given width and rounded (with awk!)

%10s

I have this and somehow I need to connect the %d but everything I do, ends up with too much parametres for awk (because I have more columns).

Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
Wanderer
  • 639
  • 3
  • 7
  • 11

3 Answers3

41

You can try this:

$ awk 'BEGIN{printf "%3.0f\n", 3.6}'
  4

Our format option has two parts:

  • 3: meaning output will be padded to 3 characters.
  • .0f: meaning output will have no precision, meaning rounded up.

From man awk, you can see more details:

width   The field should be padded to this width. The field is normally padded
        with spaces. If the 0  flag  has  been  used, it is padded with zeroes.

.prec   A number that specifies the precision to use when printing.  For the %e,
        %E, %f and %F, formats, this specifies the number of digits you want
        printed to the right of the decimal point. For the %g, and %G formats,
        it specifies the maximum number of significant  digits. For the %d, %o,
        %i, %u, %x, and %X formats, it specifies the minimum number of digits to
        print. For %s, it specifies the maximum number of characters from the
        string that should be printed.
cuonglm
  • 150,973
  • 38
  • 327
  • 406
17

Using the %f format specifier, your (floating point) number will get automatically rounded as you specify. For example, to round a value to whole numbers use

$ awk 'BEGIN { printf("%.0f\n", 1.49); }'
1
$ awk 'BEGIN { printf("%.0f\n", 1.5); }'
2

If you want further trailing digits, just change precision.

cuonglm
  • 150,973
  • 38
  • 327
  • 406
Andreas Wiese
  • 10,112
  • 1
  • 32
  • 38
7

Awk uses sprintf underneath and it does unbiased rounding, so depending on your platform if you want it to ALWAYS round up you may need to use something like this:

awk "BEGIN { x+=(5/2); printf('%.0f', (x == int(x)) ? x : int(x)+1) }"

Not realizing this can lead to subtle but nasty bugs.

Blake Barnett
  • 71
  • 1
  • 1