1

I have a very simple problem, i'm making a function that receives some floating point numbers and make a couple of operations with them at the beggining. Something like this:

function x {
    A=$1
    B=$2

# here i need a ratio, so i do, let's say..

    sum=$(($A + $B))
    C=$(($A / $sum))

[lots of code here]

}

The problem is that $1 and $2 are floating point numbers, or even if they're ints, the ratio it's very likely not to be an int, so i don't know how to operate them under bash.

I tried with a bc pipe when defining the sum and the ratio, but it outputs nothing.

Any idea is welcome! Thanks!

Ghost
  • 1,426
  • 5
  • 19
  • 38
  • possible duplicate of [how can I get a float division in bash?](http://stackoverflow.com/questions/12722095/how-can-i-get-a-float-division-in-bash) – Etheryte Dec 21 '14 at 02:52

2 Answers2

2

bc is a good idea. I don't know what you've tried; one way to do it is

C=$(echo "$A / $sum" | bc -l)
Wintermute
  • 42,983
  • 5
  • 77
  • 80
  • Perfect! I was missing the echo when defining it, thanks a lot! (4 minutes to accept the answer) :) – Ghost Dec 21 '14 at 02:56
1

With bc;

var=$(echo "scale=10; $A / $num" | bc)

echo $var

Note the scale parameter to tell bc how many decimal you want

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223