Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

i want to round off the value 262.5 to 263 using awk

i have tried the below

echo "262.5" | awk '{printf "%.f\n", $1}'

My expected answer is 263

share|improve this question

According to the GNU awk manual,

The way printf and sprintf() (see Printf) perform rounding often depends upon the system's C sprintf() subroutine. On many machines, sprintf() rounding is “unbiased,” which means it doesn't always round a trailing ‘.5’ up, contrary to naive expectations. In unbiased rounding, ‘.5’ rounds to even, rather than always up, so 1.5 rounds to 2 but 4.5 rounds to 4.

The same page also has an example round() function:

function round(x, ival, aval, fraction)
   ival = int(x)    # integer part, int() truncates

   # see if fractional part
   if (ival == x)   # no fraction
      return ival   # ensure no decimals

   if (x < 0) {
      aval = -x     # absolute value
      ival = int(aval)
      fraction = aval - ival
      if (fraction >= .5)
         return int(x) - 1   # -2.5 --> -3
         return int(x)       # -2.3 --> -2
   } else {
      fraction = x - ival
      if (fraction >= .5)
         return ival + 1
         return ival
share|improve this answer
Hi grawity, is there any option to check whether sprintf() function is unbiased or not – Bharath Oct 10 '13 at 5:58

You must log in to answer this question.

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