1833875 Members
1958 Online
110063 Solutions
New Discussion

non-integers in a script

 
SOLVED
Go to solution
Steve Sauve
Frequent Advisor

non-integers in a script

Hello all,
I'm writing a ksh script and one of the commands I run returns non-integers (numbers like 2.5, 3.2, etc). The problem comes in when I attempt to total the returns. I was first using x=`expr $x + $y` and that was choking on the fact that $y wasn't an integer. I then tried ((x=$x+$y)) and though that would produce a result, it just truncated everything after the decimal point.
I've dug around a bit and haven't discovered how to work with non-integers. Any help would be appreciated. Thanks :)
Steve
2 REPLIES 2
James R. Ferguson
Acclaimed Contributor
Solution

Re: non-integers in a script

Steve:

You must use 'bc' to do real number arithmetic.

# echo "scale=2\n 10/4" | bc

...returns 2.50

Make sure you provide enough precision in the scale statement. For instance:

# echo "11/4" | bc

...returns "2", and:

# echo "scale=1\n 11/4" | bc

...returns "2.7", and:

# echo "scale=2\n 11/4" | bc

...returns "2.75"

...JRF...
Gregory Fruth
Esteemed Contributor

Re: non-integers in a script

Or maybe awk...

x=10.1
y=20.2
awk -vx=$x -vy=$y 'BEGIN {z=x+y; print z;}'
awk -vx=$x -vy=$y 'BEGIN {z=cos(x)+sin(y); print z;}'