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?
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.Sign up to join this community
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
/ to have their natural precedence
$ bash -c 'echo $(( ($1-32)*5/9 ))' bash 35 1
15, which when integer-divided by
1. If you actually want floating point arithmetic then you can use an external program such as
$ 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 -c 'echo $(( ($1-32)*5/9 ))' ksh 35.0 1.66666666666666667
(note the use of argument
35.0 to force floating point promotion).