0

I need to count variables, round to 2 and store to variable.

Example:

I have variable from array ${array[5]} and vat variable defined, I need to calculate simple

( $vat * ${array[5]} + ${array[5]} )

and store to variable pricevat.

I tried:

vat = 0.21

pricevat=$(echo "$vat * ${array[5]}" + ${array[5]} | bc -l)
(( pricevat=$vat*${array[5]}+${array[5]}))

But nothing works:

line 48: ((: pricevat=0.21*0.233+0.233: syntax error: invalid arithmetic operator (error token is ".21*0.233+0.233"

Could you help me please? Where is the problem? What is best solution for this. Thank you very much.

S.

  • 2
    `((...))` can't do floating-point arithmetic, which is the source of the error. The previous line works fine. – chepner May 23 '19 at 22:02

2 Answers2

0

On possibility (though, it will not round, but truncate to 3 decimal places):

array=( ... ... ... ... ... 102.03 ... )
vat=0.21
pricevat=$(bc <<< "scale=3; (1+$vat)*${array[5]}")

The trick is to have bc do the rounding, using its special variable scale, set to 3.

gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
  • Did you already try: `mkfifo fifo;exec 7> >(exec stdbuf -i 0 -o 0 bc -l >fifo);exec 6&7 "scale=3;(1+$vat)*${array[5]}";read -u 6 -t .01 result`... So you could ask for many operation using `FD7` and `FD6` (keeping `scale=3` as long you don't change them;)... – F. Hauri - Give Up GitHub Sep 24 '19 at 19:38
-1

Yes, it is working! I did it like this.

Arithmetic operations:

pricevat=$(echo "$vat * ${array[5]}" + ${array[5]} | bc -l)

Round to 3 places:

pricevat=$(printf "%0.3f\n" $pricevat)

If there is another way to do it better or together on one line, let me know please.

Thanks.