linux + ksh + Round down or Round up - float numb

2019-06-24 19:11发布

问题:

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

回答1:

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).

printf "%0.f\n" 4.51
5
printf "%0.f\n" 4.49
4

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:

perl -MMath::Round -we 'print round $ARGV[0]' 12.49

Script:

use v5.10;
use Math::Round;
my @list = (3.49, 2.9, 4.1, 23.51, 982.4999);

say round $_ for @list;

Script output:

3
3
4
24
982


回答2:

In awk you can use the int() function to truncate the values of a floating point number to make it integer.

[jaypal:~/Temp] cat f
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

[jaypal:~/Temp] awk '{x=int($1); print $0,x}' f
3.49     will be 3 3
2.9      will be 3 2
4.1      will be 4 4
23.51    will be 24 23
982.4999 will be 982 982

To Round off you can do something like this -

[jaypal:~/Temp] awk '{x=$1+0.5; y=int(x); print $0,y}' f
3.49     will be 3 3
2.9      will be 3 3
4.1      will be 4 4
23.51    will be 24 24
982.4999 will be 982 982

Note: I am not sure how you would like to handle numbers like 2.5. The above method will return 3 for 2.5.



回答3:

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:

$ y=3.49
$ print $(( round(y) ))
3
$ y=3.51
$ print $(( round(y) ))
4
$ (( p = round(y) ))
$ print $p
4
$


回答4:

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 a Math.round function which could be used directly.