1748227 Members
4397 Online
108759 Solutions
New Discussion юеВ

Re: Scripting issue

 
SOLVED
Go to solution
Dewa Negara_4
Regular Advisor

Scripting issue

Hi All,

I want to calculate the space using a script. When I used some command below, it gave me result 0.

PCT=44
USED=45260.8
((FLOATPCT=PCT / 100))
((TOTUSED=$FLOATPCT * $USED))
echo $FLOATPCT
echo $TOTUSED

Both was giving me 0 result. How can I modify the script, so the result of FLOATPCT=0.44 and TOTUSED=19914.752 instead?

Pls help.

Thanks and Best Regards,
Negara
Santos
5 REPLIES 5
Hemmetter
Esteemed Contributor
Solution

Re: Scripting issue

Hi Negara

Shell does only integer math.

You may try someting like this:

# echo "scale=2 ; $PCT/100" | bc
.44

uxmp0001:/root# echo "scale=2 ; $PCT/100*$USED" | bc
19914.75



rgds
HGH
James R. Ferguson
Acclaimed Contributor

Re: Scripting issue

Hi Negra:

Another way is to use 'swk':

# awk -v PCT=44 -v USED=45260.8 'BEGIN{printf("%.2f\n",(PCT/100)*USED)}'

19914.75

Regards!

...JRF...
Bill Hassell
Honored Contributor

Re: Scripting issue

The ksh and POSIX shells on HP-UX have only integer math, no floating point. The ksh on HP-UX is ksh-1988 and the POSIX shell is based on the same code. You need ksh-1993. Change your script interpreter to use /usr/dt/bin/dtksh as your shell interpreter. Also, you cannot use integer numbers and expect them to be converted to floating point. Change your script to read like this:

#!/usr/dt/bin/dtksh
typeset -F PCT=44.0
typeset -F USED=45260.8
((FLOATPCT=PCT / 100))
((TOTUSED=$FLOATPCT * $USED))
echo $FLOATPCT
echo $TOTUSED

This now gives you the expected answers. Unfortunately, the HP man page for dtksh covers mostly the Xwindow enhancements and doesn't talk at all about typeset and integer versus floating point variables and math. Use this as your dtksh resource page:

http://www.kornshell.com/doc/


Bill Hassell, sysadmin
Dewa Negara_4
Regular Advisor

Re: Scripting issue

Hi All,

Thanks alot for your help. It's clear for me now.

Best regards,
Negara
Santos
Dennis Handly
Acclaimed Contributor

Re: Scripting issue

>HGH: Shell does only integer math.

You can simulate it by multiplying the numerator by 10 to the power of the number of fractional digits, then manually placing the decimal point.

Of course this won't work well if the number overflows before the divide.