-3

how to calculate float numbers: with bash

example

     DRIVER_MEMORY=$(( 5 * 0.6 * 0.9 ))
-bash: 5 * 0.6 * 0.9 : syntax error: invalid arithmetic operator (error token is ".6 * 0.9 ")

remark - results must be integer number - so we can round the number to down

jesse_b
  • 37,005
jango
  • 423
  • What is it you want though: bash, awk, or bc? – jesse_b Feb 12 '18 at 13:40
  • no matter but the best elegant approach – jango Feb 12 '18 at 13:41
  • 1
    http://idownvotedbecau.se/noresearch/ – Murphy Feb 12 '18 at 13:54
  • bash doesn't do float. The syntax error really means "error: input not an integer". DRIVER_MEMORY=$((5*6*9/100)) or DRIVER_MEMORY=$(((5*6*9+50)/100)) does this calculation (depending on your desired rounding mode) if you want to avoid forking out another process – Fox Feb 12 '18 at 14:09
  • Write your own function for multiplication. Here is an example of an integer division with floating point results. – Cyrus Feb 12 '18 at 19:17

1 Answers1

0

Awk solution:

 DRIVER_MEMORY=$( awk '{ print 5*0.6*0.9 }' <<< "")

bc solution:

DRIVER MEMORY=$(echo "5*0.6*0.9" | bc)
  • 2
    You could use a BEGIN statement instead of the null string redirect: DRIVER_MEMORY=$(awk 'BEGIN{print 5*0.6*0.9}') – jesse_b Feb 12 '18 at 14:03