Operating System - HP-UX
1829148 Members
2555 Online
109986 Solutions
New Discussion

How to calculate decimal number ?

 
SOLVED
Go to solution
Patrick Chim
Trusted Contributor

How to calculate decimal number ?

If I run `expr 1 / 2` it will output 0.
How can I write a script to generate the result 0.5 ?
Thanks !
5 REPLIES 5
Dave Kelly_1
Respected Contributor
Solution

Re: How to calculate decimal number ?

You can try

echo "scale=2 ; 1 / 2" | bc
Thomas Kollig
Trusted Contributor

Re: How to calculate decimal number ?

I had the same problem. I just wrote a little C++ program (for multiplication):

int main(int argc, char ** argv)
{
cout << atof(argv[1]) * atof(argv[2]) << endl;
}

Then you can use this program in your script to calculate decimal numbers.
Dan Hetzel
Honored Contributor

Re: How to calculate decimal number ?

Hi Patrick,

'expr' won't give you anything but integers.
If you want nearly unlimited precision, you should use 'bc' like this:
echo "scale=2\n5/2" | bc

Result will be 0.50 as expected.
Adjust the scale according to your needs.


Best regards,

Dan

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

Re: How to calculate decimal number ?

Hi Patrick,

If you have many operations to do in your script, you could use a two-way pipe to 'bc' instead of running bc many times.

#!/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
Curtis Larson
Trusted Contributor

Re: How to calculate decimal number ?

you could use a shell that supports floating point arithmetic:

#!/usr/dt/bin/dtksh

float x
x=1.0/2 #one has to be floating point or it will perform integer arthimetic
print $x