Bash Multiply decimal by int

I read the price from user input. When I multiply input with int this way

T = "$((PRICE*QTY))"|bc ; gives the line 272: 12.00: syntax error: incorrect arithmetic operator (error marker is ".00") or .50

depending on user input. How can I multiply these two variables and get the total with two decimal points?

+6
decimal bash multiplication
source share
4 answers

it works:

 PRICE=1.1 QTY=21 RES=$(echo "scale=4; $PRICE*$QTY" | bc) echo $RES 
+13
source share
 var=$(echo "scale=2;$PRICE*$QTY" |bc) 

You can also use awk

 awk -vp=$PRICE -vq=$QTY 'BEGIN{printf "%.2f" ,p * q}' 
+4
source share
 T="$(echo "$PRICE*$QTY" | bc)" 
+2
source share

Firstly, trying to do floating point arithmetic with bc(1) without using the -l flag should give you some funny answers:

 sarnold@haig :~$ bc -q 3.5 * 3.5 12.2 sarnold@haig :~$ bc -q -l 3.5 * 3.5 12.25 

Secondly, $((...)) is an attempt to perform arithmetic in your shell; neither my bash nor dash can handle floating point numbers.

If you want to do arithmetic in your shell, pay attention to printf(1) , as well as (possibly) the built-in printf shell function. If you want to do arithmetic in bc, pay attention to the special variable scale .

0
source share

All Articles