1833163 Members
3246 Online
110051 Solutions
New Discussion

Calculation in Ksh !

 
SOLVED
Go to solution
Chris Fung
Frequent Advisor

Calculation in Ksh !

Hi all,

I am just wondering whether I can do decimal calculation in Ksh environment !!

I have tried to calcuate 10/100 in Ksh and the result will be integer 0

Can I create and control the number of decimal point e.g. 0.1 or 0.10 for the above calcuation ??

Many thanks

Chris,
6 REPLIES 6
A. Clay Stephenson
Acclaimed Contributor

Re: Calculation in Ksh !

In a word, no. All shell arithmatic is integer not floating point. You can easily use bc, awk, or Perl to do this calculations and return them to the shell.

A Forums search will reveal many different approaches.
If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: Calculation in Ksh !

Hi Chris:

Using 'bc' is easy and offers a choice of the input and output base, scale and length of output. For instance:

# X=`echo "ibase=16;F+F;obase=10"|bc`;echo ${X}

# Y=`echo "scale=3;1/8"|bc`;echo ${Y}

Regards!

...JRF...
Dave La Mar
Honored Contributor

Re: Calculation in Ksh !

Chris,
Though it would be best to get used to using the utilities previously mentioned, in a down and dirty, simply multiply by 100.
I have done this quite often in simple scripts then set the decimal point to get percentages, etc.

Best of luck.

Regards,

dl
"I'm not dumb. I just have a command of thoroughly useless information."
curt larson_1
Honored Contributor

Re: Calculation in Ksh !

Mr. Stephenson is pretty much right (All shell arithmatic is integer not floating point). But, not absolutely. only korn shell versions newer then the 11/16/88 version have floating point arithmetic. unfortunately for you /usr/bin/ksh is the 11/16/88 version.

but /usr/dt/bin/dtksh does include most of the 93 version of the korn shell features including floating point arithmetic. So you
can do something like this if you like.

#!/usr/dt/bin/dtksh

typeset -F a=3 b=4 c # specify the floating point attribute

c=$(( $a/$b ))
print $c

#or
printf "%4.3f\n" $(( $a/$b ))
Tim D Fulford
Honored Contributor
Solution

Re: Calculation in Ksh !

No....

try awk

a=10
b=100
c=$(echo $a $b | awk '{print $1/$2}')
echo $c

If you want to format the output
c=$(echo $a $b | awk '{printf "%10.2f", $a/$b}')

Regards

Tim
-
Elena Leontieva
Esteemed Contributor

Re: Calculation in Ksh !

ksh93 can do floating-point arithmetic.