Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to perform arithmetic operations in a shell script

Status
Not open for further replies.

Ambatim

Programmer
Feb 28, 2002
110
IN
Suppose if I have two variable A and B. I want the result of A divided by B in C.
I tried with expr command, as shown below, but it is giving the error

A=3.75
B=3
C=`expr $A / $B`

expr: 0402-046 A specified operator requires numeric parameters.

Thanks in advance
Mallik
 
man bc

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Ambatim:

The sh/ksh/bash shells only support integer aritmetic. Only ksh93 or one of it's cousins, pdksh, dtksh, supports decimal:

#!/usr/dt/bin/dtksh

x=$((1000005.0/2))
echo $x # 500002.50

otherwise you'll have to take PHV's bc suggestion.

 
Thanks Guys...
Now I could get the result using bc.

But how can I round (not truncate) the result from bc to two decimals. Currently it returns 20 decimals

Thanks in advance
Mallik
 
for 'bc' use 'scale=2'

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Thanks Guys....

I have another problem...How to compare decimal values...for example I have
A=0.02
B=0.03
if [ $B -gt $A ]; then
echo "B is greater than A"
else
echo "B is not greater than A"
fi

Even though B is greated than A, this is printing B is not greater than A
Any ideas

Thanks in advance
Mallik
 
same idea as before....
Code:
#!/bin/ksh

typeset a=1.72
typeset b=1.73

if [ "$(echo "if (${a} > ${b}) 1" | bc)" -eq 1 ] ; then
   echo ">"
else
   echo "<"
fi;

vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
#!/usr/dt/bin/dtksh

float a=1.72
float b=1.73

if [[ $b -gt $a ]]; then
print "$b is greater than $a"
else
print "$b is not greather than $a"
fi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top