Linux + ksh + Round down or Round up - float numbers

in my ksh script I need to calculate only integers

Sometimes I get floating point numbers like 3.49 or 4.8 ... etc.

so I need to translate floating point numbers to integers in accordance with 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 advise how to do this in ksh or awk or perl

Or

any other language that can be run in my ksh script

+4
source share
4 answers

After a short Google session, I found that printf seems to be able to do the job, at least in bash (could not find the online interpreter that ksh does).

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

Code at: http://ideone.com/nEFYF

Note: perl may be redundant, as Marius says, but here is the perl path:

The perl Math :: Round module seems to be handling the job.

Single line:

 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 
+4
source

In awk you can use the int() function to truncate the values ​​of a floating-point number to make it an 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'm not sure how you would like to handle numbers like 2.5 . The above method will return 3 for 2.5 .

+4
source

Versions of ksh that do non-integer math may have functions floor (), trunc (), and round (). I can not check them all, but at least on my Mac (Lion), I get the following:

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

In perl, my $i = int($f+0.5); . It should be similar in another, assuming that they have a function to convert to whole or floor. Or, if they are similar to javascript, they have a Math.round function that can be used directly.

0
source

Source: https://habr.com/ru/post/1389890/


All Articles