1

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?

Eliah Kagan
  • 117,780

1 Answers1

9

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
0

if you allow * and / to have their natural precedence

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

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
1.65

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

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

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

steeldriver
  • 136,215
  • 21
  • 243
  • 336
  • 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 09 '19 at 17:28