Operating System - HP-UX
1836987 Members
2267 Online
110111 Solutions
New Discussion

How to get deicmal results in shell.

 
SOLVED
Go to solution
Patrick Provenzo
Frequent Advisor

How to get deicmal results in shell.

I am trying to write a shell script that divides 2 numbers and retuns the result to two decimal places. With expr I only get the integer result. How can I get the decimal result?
3 REPLIES 3
James R. Ferguson
Acclaimed Contributor
Solution

Re: How to get deicmal results in shell.

Hi Patrick:

Most shells only support integer arithmetic.

# X=100;Y=25;((Z=X/Y));echo $Z

If you want to incorporate real numbers, 'bc' provides a convenient vehicle. Choose the 'scale' to set the precision you want:

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

You can also leverage 'awk' and couple it with 'printf' to format output, including moving to a different number base:

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

# X=7;Y=8;echo "$X $Y"|awk '{printf "%4x\n",$1+$2}'

If you use the Korn93 shell, its 'typeset' allows a more direct approach to real numbers:

#!/usr/dt/bin/dtksh
typeset -F R1
typeset -F3 R2
typeset -E R3
let R1=1/8
echo $R1
let R2=1/8
echo $R2
let R3=1/8
echo $R3
exit 0

Regards!

...JRF...
Patrick Provenzo
Frequent Advisor

Re: How to get deicmal results in shell.

Using bc worked great. Still haven't gotten the awk ones to work, but bc will do thanks.
Tor-Arne Nostdal
Trusted Contributor

Re: How to get deicmal results in shell.

ehhh...a little cheating...

You could work with integers if you just multiply with 100 before calculating, then insert a . afterwards as the decimal separator ;-)

/Tor-Arne
I'm trying to become President of the state I'm in...