When I type in the following commands:

result=$(( ($1-32)*(5/9) ))
echo $result

the variable, result, always evaluates to an integer, whether the equation evaluates to a decimal number or not. Why is this?


The bash shell natively only supports integer arithmetic. In particular, since 5 is less than 9, (5/9) will evaluate to zero regardless of the other terms in your product.

Depending on your requirements, you might be able to do what you want (still using integer arithmetic) by changing the order of operations i.e. whereas

$ bash -c 'echo $(( ($1-32)*(5/9) ))' bash 35

if you allow * and / to have their natural precedence

$ bash -c 'echo $(( ($1-32)*5/9 ))' bash 35

because (35-32)*5 is 15, which when integer-divided by 9 yields 1. If you actually want floating point arithmetic then you can use an external program such as bc or awk e.g.

$ bash -c 'echo "scale = 2; ($1-32)*(5/9)" | bc' bash 35

or switch to a shell that supports floating point arithmetic, such as ksh:

$ ksh -c 'echo $(( ($1-32)*5/9 ))' ksh 35.0

(note the use of argument 35.0 to force floating point promotion).

  • var=35; <<<"scale = 3; ($var-32)*5/9" bc maybe helps explaining. It corresponds to the command line var=35; echo "scale = 3; ($var-32)*5/9" | bc – sudodus Sep 9 '19 at 17:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.