Operating System - HP-UX
1820591 Members
1829 Online
109626 Solutions
New Discussion юеВ

How can I do floating point arithmetic in ksh ?

 
SOLVED
Go to solution
Richard Quinn
Occasional Advisor

How can I do floating point arithmetic in ksh ?

I know I should know this but ...
Every time I try to do floating point aithmetic it detaults to integer values. e.g.
> x=1.1; echo $x
1.1
> let "x=x+1.5"; echo $x
2
> let "x=x+1.9" ; echo $x
3
4 REPLIES 4
Dan Hetzel
Honored Contributor

Re: How can I do floating point arithmetic in ksh ?

Hi Richard,

As shells default to integer arithmetic, the only way I know to enable real arithmetic is through 'bc'

You could use the 'two way pipe' to the program to do all your math operations, like this:
#!/usr/bin/sh
# This starts bc with a two-way pipe
bc |&
# print -p writes to the pipe
print -p scale=2
print -p 3/4
# read -p reads from the pipe
read -p myvar
echo $myvar

The script here above will echo '.75'

see manual for sh-posix

Best regards,

Dan
Everybody knows at least one thing worth sharing -- mailto:dan.hetzel@wildcroft.com
RikTytgat
Honored Contributor
Solution

Re: How can I do floating point arithmetic in ksh ?

Hi,

You can use bc(1).

Example:

x=2.5
y=3.456
res=$(echo "scale=4\n$x * $y" | bc)

res will be 8.6400.

See manpage for more details.


Hope this helps,
Rik


James R. Ferguson
Acclaimed Contributor

Re: How can I do floating point arithmetic in ksh ?

Hi Richard:

Certainly, 'bc' is the first tool that springs to mind for dealing with real numbers in shells. 'awk' can also be used:

Thus, either:

# X=1;Y=8;echo "scale=3\n $X / $Y" | bc

...or....

# X=1;Y=8;echo "$X $Y" | awk '{printf "%.4f\n",$1 / $2}'

Regards!

...JRF...
Curtis Larson
Trusted Contributor

Re: How can I do floating point arithmetic in ksh ?

you could just use a shell that supports floating point numbers:

#!/usr/dt/bin/dtksh

float x=5 y=3 z
print $(( z = $x/$y)) #or
printf "%.4f\n" $(( z = $x/$y ))