Dividing two numbers in unix

Hi,

I have written this code the division of two numbers and multiply it by hundred (to get the percent)

echo "script running for the 1st time"
cp value_directory_present.txt /home/mysql_cnbc/value_directory_past.txt
rm -f test6.txt value_directory_present.txt
else
y1=`awk '{print $1}' value_directory_past.txt`
z=`expr $y - $y1`
echo $z
if [ $z = 0 ];then
echo "rate is zero"
rm -f value_directory_present.txt test6.txt test7.txt
break
else
z1=`$z/$y1`
echo $z1
z2=`100 * $z1`

when i am executing it i am getting this error .

+ find . -type f -name value_directory_past.txt
+ var=./value_directory_past.txt
+ [ ./value_directory_past.txt == '' ]
+ awk '{print $1}' value_directory_past.txt
+ y1=23789264
+ expr 23789328 - 23789264
+ z=64
+ echo 64
64
+ [ 64 = 0 ]
+ 64/23789264

test4.sh: line 32: 64/23789264: not found

+ z1=''
+ echo

Please suggest.:o

odd... you know to use "expr" here:

z=`expr $y - $y1`

and then forget to use it here:

z1=`$z/$y1`

The answer would be:

z1=`expr $z/$y1`

---------- Post updated at 10:14 AM ---------- Previous update was at 10:13 AM ----------

you will have a similar issue with z2 as well.

after using expr i am getting some garbage value while executing

+ expr 68/23789332
+ z1=68/23789332
+ echo 68/23789332
68/23789332
+ expr 100 0 $'0�\E' '06:03:59] 06:08:50 06:09:20 06:11:00 06:12:47 15837921 '�:5Q6 $'Aborted\nAborted\nAborted]'
expr: syntax error
 
+ z2='
+ echo 'rate is %

I'd use bc instead of expr for this. With bc you can define the number of digits after the decimal point.

$ x=64
$ z=$(echo "scale=10; $x / 23789264 * 100" |bc)
$ echo $z
.0002690200
$ z=`expr $x / 23789264`
$ z1=`expr $z \* 100`
$ echo $z1
0
$

Edit: you need spaces around the devision mark with any of those techiques...

1 Like

In integer arithmetic, always do your multiples before your divides.
However with these numbers the answer is always going to be zero because the percentage is so small.

If you need to see the actual value, try the bc command set to say six decimal places:

echo "scale=6;((64 * 100) / 23789264)"|bc

.000269

Note that very few shells can deal with decimal places in numbers.

Edit: Post crossed with cero.

1 Like

i can not multiply the difference before divison as i am trying to find out percentage change.

Any other way to get percentage?:o