Operating System - HP-UX
1753366 Members
5953 Online
108792 Solutions
New Discussion

Re: calculating variables with decimals

 
SOLVED
Go to solution
lawrenzo
Trusted Contributor

calculating variables with decimals

Hi,

 

in ksh scripting can someone tell me how to calculate decimal numbers ie:

 

sz=0.5

msz=$(($sz*1024))

echo $msz

0

 

I know printf will help me out but not sure of the syntax

 

Thanks

 

Chris

hello
6 REPLIES 6
Hein van den Heuvel
Honored Contributor

Re: calculating variables with decimals

SOL

 

Shells typically deal with integer only.

 

You can  store the decimal values a piece of string, but the math will be integer.

You will have to reach out to a tool like 'bc' to do the floating point math.

 

I suspect that the script you are working with is more about parsing and juggling numbers and string

than it is about issuing commands

If so, then personally I would just step into AWK or PERL and do all of those chunks of script there.

 

Good luck!

Hein

 

James R. Ferguson
Acclaimed Contributor

Re: calculating variables with decimals

Hi:

 

In addition to using 'bc', 'awk' or Perl as Hein has advised, you could leverage the 'dtksh' shell in lieu of the 'ksh' one.  The 'dtksh' shell is a Korn93 variant whereas the 'ksh' one of HP-UX is Korn88.

 

You can find 'dtksh' as '/usr/dt/bin/dtksh' (which requires installlation of the CDE bundle on 11.31).

 

 

# cat ./mycalc
#!/usrb/dt/bin/dtksh
typeset -E MSZ
typeset -E SZ=.5
MSZ=$((SZ*1024))
echo ${MSG}
exit 0

# ./mycalc

512

 

Regards!

 

...JRF...

Laurent Menase
Honored Contributor

Re: calculating variables with decimals

in ksh you can also do fix point calculation , if you don"t deal with too small or too large numbers

 

For instance

 

If you want to calculate all with 2 decimal digits.

 

# sz=50
# msz=$(($sz*1024))
# printf "%d.%02d\n" $((msz/100)) $((msz%100))   
512.00

 

(10.24 + 11.35)*2.35

you do

typeset  -i res

res=$(((1024*1035)*235))

# printf "%d.%04d\n" $((res/10000)) $((res%10000))

24906.2400

 

 

 

lawrenzo
Trusted Contributor
Solution

Re: calculating variables with decimals

ok great thanks for the info everyone.

 

Chris

hello
Dennis Handly
Acclaimed Contributor

Re: calculating variables with decimals

>in ksh you can also do fix point calculation

 

Yes, exactly what COBOL does automatically.

Laurent Menase
Honored Contributor

Re: calculating variables with decimals

>>in ksh you can also do fix point calculation

>Yes, exactly what COBOL does automatically.

Or old assembly uses when floating point coproc was not so common.

In most case it is enough in scripts, keeping an implicit exponent, it is just basic arithmetic