in my ksh script I need to calculate only integer numbers
Sometimes I get float numbers such as 3.49 or 4.8...etc
so I need to translate the float numbers to integer’s numbers according to the following rules (examples)
3.49 will be 3
2.9 will be 3
4.1 will be 4
23.51 will be 24
982.4999 will be 982
10.5 will be 11 ( this example if float is .5 then it will roundup )
Please advice how to do this in ksh or awk or perl
Or
any other language that can be run in my ksh script
Versions of ksh that do non-integer math probably have floor(), trunc(), and round() functions. Can't check 'em all, but at least on my Mac (Lion), I get this:
In perl,
my $i = int($f+0.5);
. Should be similar in the other, assuming they have a convert to integer or floor function. Or, if like in javascript, they have aMath.round
function which could be used directly.After a brief google session, I found that
printf
seems to be able to do the job, at least in bash (couldn't find an online interpreter that does ksh).Code at: http://ideone.com/nEFYF
Note: perl might be overkill, like Marius says, but here's a perl way:
The perl module Math::Round seems to handle the job.
One-liner:
Script:
Script output:
In
awk
you can use theint()
function to truncate the values of a floating point number to make it integer.To Round off you can do something like this -
Note: I am not sure how you would like to handle
numbers like 2.5
. The above method will return3 for 2.5
.