The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
Google UNIX.COM


Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts here.

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
Round the column value : satyam_sat Shell Programming and Scripting 4 04-10-2008 08:30 AM
Srry Im a bit new round here..... BigDaddyDirt UNIX for Dummies Questions & Answers 3 03-17-2008 11:54 AM
round a number achieve Shell Programming and Scripting 2 09-14-2006 01:23 AM
round in KSH here2learn Shell Programming and Scripting 6 07-18-2006 09:18 AM
how to round a value kotasateesh UNIX for Dummies Questions & Answers 2 02-08-2006 01:38 PM

Reply
 
Submit Tools LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 05-06-2008
Registered User
 

Join Date: Mar 2008
Posts: 9
Stumble this Post!
Round with awk

Hi, I have a problem. Basically I dont know how to use awk. I have a script (below) which works fine.

What I want to do is somehow "pipe" in the input say 4.5 and have it give the anwer, I dont want ot have to type it in, since it will be running in a script.

Any ideas how to do this????


# round.awk --- do normal rounding


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

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

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
}
}


# test harness
{ print round($0)
exit 1
}
Reply With Quote
Forum Sponsor
  #2 (permalink)  
Old 05-06-2008
Moderator
 

Join Date: Feb 2007
Posts: 1,953
Stumble this Post!
Another way instead of a function to accomplish this:

Code:
echo "4.5" | awk '{printf("%d\n",$0+=$0<0?-0.5:0.5)}'
Regards
Reply With Quote
Google The UNIX and Linux Forums
Reply

Thread Tools
Display Modes




All times are GMT -7. The time now is 01:27 PM.


Powered by: vBulletin, Copyright ©2000 - 2006, Jelsoft Enterprises Limited.
The UNIX and Linux Forums Content Copyright ©1993-2008 The CEP Blog All Rights Reserved -Ad Management by RedTyger Visit The Global Fact Book

Content Relevant URLs by vBSEO 3.2.0