Operating System - HP-UX
1753856 Members
7272 Online
108809 Solutions
New Discussion юеВ

ksh mutliply 0.2 constant with value and output

 
SOLVED
Go to solution
Susan Prosser
Advisor

ksh mutliply 0.2 constant with value and output

Please can someone tell me what I am doing wrong!!

I want to mulitply a VALUE=100
with a CONSTANT=0.02 and display the results with decimal places.

If I try ...

(( NUM = 100 * 0.2 ))
printf "Answer is %4.2f\n" , $NUM

The result comes back as
Answer is 44.00
Answer is 0.00

Any ideas
Thanks

when I am want 20
5 REPLIES 5
Joseph C. Denman
Honored Contributor

Re: ksh mutliply 0.2 constant with value and output

Try:

NUM=`expr 100 \* 2 / 10`
printf "Answer is %4.2f\n" , $NUM

Hope this helps.

...jcd...
If I had only read the instructions first??
Robin Wakefield
Honored Contributor
Solution

Re: ksh mutliply 0.2 constant with value and output

Kevin,

(( .... )) syntax is integer only.

Use something like bc:

# echo "100*0.2" | bc | read NUM
# printf "%4.2f\n" $NUM
20.00

Rgds, Robin
Tom Maloy
Respected Contributor

Re: ksh mutliply 0.2 constant with value and output

The comma is causing the second line of output. Without the comma, just get 0.00.

ksh does integer arithmetic. 0.2 rounds to integer 0, so the multiplication produces 0.

Can you do

(( NUM = 100 * 2 / 10 ))

This will produce 20.

Tom
Carpe diem!
Hai Nguyen_1
Honored Contributor

Re: ksh mutliply 0.2 constant with value and output

Kevin,

Try this simple awk command:

# echo | awk '{print 100 * 0.2}'

Hai
Joseph C. Denman
Honored Contributor

Re: ksh mutliply 0.2 constant with value and output

Kevin,

Robin is correct. You will need to use something like bc.

My above example, though produces the correct output for the example, will give an incorrect response in the event of a fraction.

...jcd...
If I had only read the instructions first??