Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

1 Answer 1

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
      else
         return int(x)       # -2.3 --> -2
   } else {
      fraction = x - ival
      if (fraction >= .5)
         return ival + 1
      else
         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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.