gawk: Round Function

1 
1 10.2.3 Rounding Numbers
1 -----------------------
1 
1 The way 'printf' and 'sprintf()' (⇒Printf) perform rounding often
1 depends upon the system's C 'sprintf()' subroutine.  On many machines,
1 'sprintf()' rounding is "unbiased", which means it doesn't always round
1 a trailing .5 up, contrary to naive expectations.  In unbiased rounding,
1 .5 rounds to even, rather than always up, so 1.5 rounds to 2 but 4.5
1 rounds to 4.  This means that if you are using a format that does
1 rounding (e.g., '"%.0f"'), you should check what your system does.  The
1 following function does traditional rounding; it might be useful if your
1 'awk''s 'printf' does unbiased rounding:
1 
1      # round.awk --- do normal rounding
1 
1      function round(x,   ival, aval, fraction)
1      {
1         ival = int(x)    # integer part, int() truncates
1 
1         # see if fractional part
1         if (ival == x)   # no fraction
1            return ival   # ensure no decimals
1 
1         if (x < 0) {
1            aval = -x     # absolute value
1            ival = int(aval)
1            fraction = aval - ival
1            if (fraction >= .5)
1               return int(x) - 1   # -2.5 --> -3
1            else
1               return int(x)       # -2.3 --> -2
1         } else {
1            fraction = x - ival
1            if (fraction >= .5)
1               return ival + 1
1            else
1               return ival
1         }
1      }
1      # test harness
1      # { print $0, round($0) }
1