0

I need to perform some arithemic with bash.It goes like this

VariableA = (VariableB-VariableC) / 60

Variable A should be approximated to 2 decimal places

I don't know which one of these is the right answer(Don't have a linux server at hand atm to test)

VariableA = $((VariableB-VariableC)/60)

VariableA = $(((VariableB-VariableC)/))/60)

It would be nice if someone could also help me out about how to round the VariableA to 2 decimal places without using third party tools like bc

user2650277
  • 6,289
  • 17
  • 63
  • 132
  • none of your line would work. in shell script assignment statement is like `VarA=Foo`, no spaces before/after the `=` – Kent May 15 '14 at 13:47
  • The syntax seems to be $((SOME_CALC)), where SOME_CALC is your calculation. So both your examples are wrong, try it with `$(((VariableB-VariableC) / 60))` – stuXnet May 15 '14 at 13:47
  • If you want to test your bash code without having a bash shell in front of you, you can use the bash shell portion of [Compile Online](http://www.compileonline.com/execute_bash_online.php). – Alex A. May 15 '14 at 13:49
  • @Kent i knew about it ...i just put the spaces by mistake when writing this post.@stuXnet thanks ... – user2650277 May 15 '14 at 13:49

1 Answers1

2

The bash itself can compute only integer values, so if you need to use a fixed number of decimals, you can shift your decimal point (it's like computing in cents instead of dollars or euros). Then only at the output you need to make sure there's a . before the last two digits of your number:

a=800
b=300
result=$((a*100/b))  # factor 100 because of division!
echo "${result:0:-2}.${result: -2}"

will print 2.66.

If you want to make computations in floating points, you should use a tool like bc to do that for you:

bc <<<'scale=2; 8.00/3.00'

will print out 2.66.

anishsane
  • 20,270
  • 5
  • 40
  • 73
Alfe
  • 56,346
  • 20
  • 107
  • 159