views:

49

answers:

4

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

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

depending on user input. How do i multiply these two variables and get a total with 2 decimal points?

+1  A: 
T="$(echo "$PRICE*$QTY" | bc)"
Ignacio Vazquez-Abrams
i get (standard_in) 2: syntax erroridk why. its almost the same as above
svenus
@svenus: This one works for me. I don't know why you're getting that error from `bc`.
Dennis Williamson
A: 
var=$(echo "scale=2;$PRICE*$QTY" |bc)

You can also use awk

awk -vp=$PRICE -vq=$QTY 'BEGIN{printf "%.2f" ,p * q}'
ghostdog74
./menu3.sh: line 278: 12.25: syntax error: invalid arithmetic operator (error token is ".25")
svenus
remove the `$(())` . bash doesn't do floating arithmetic. If you want to set 2 decimal places, use scale=2
ghostdog74
You need dollar signs before each variable name.
Dennis Williamson
var=$(echo "scale=2;$PRICE*$QTY" |bc) gives me(standard_in) 2: syntax error
svenus
edited. left out the dollar sign
ghostdog74
+1  A: 

this works:


PRICE=1.1
QTY=21
RES=$(echo "scale=4; $PRICE*$QTY" | bc)
echo $RES
loentar
ha!! That totally works too! I missed the echo. Thanks!
svenus
A: 

First, trying to do floating-point arithmetic with bc(1) without using the -l flag is bound to 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

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

If you want to do the arithmetic in your shell, note printf(1) as well as (probably) your shell's built-in printf function. If you want to do the arithmetic in bc, note the special variable scale.

sarnold
most of the $(( )) with bc i tried gave me errors. Must be because of the (( ))? Thanks for the clarification.
svenus