While writing some shell/bash scripts some times we my need to do multiplication or division that will for sure generate floating point numbers.

Recently I got struggled with this problem, did little bit exploration to resolve this issue.

I will use **bc**** **command to do basic math operations.

If we want to divide 2 with 5 using bc use following procedure

**$ echo 2/5 | bc**

Output: 0

But the above output is wrong.

To get proper floating point number there is a variable called scale. Scale means the precision of floating point, how many digit after the point. By default the scale is 0, that means it is integer.

Above example can be solved with scale to get correct output as shown below.

$ echo "scale=2; 2/5" | bc

Output: .40

Here I am using scale value as 2, that will give 2 digits after the floating point number so we got output .40

-Sany

### Like this:

Like Loading...

*Related*

Right, but try it with multiplication. That is, compare the outputs of:

echo “scale=2;57/43.1234567” | bc

and

echo “scale=2;57*43.1234567” | bc

“scale” is honored in the first one but not the second. For reasons I cannot even begin to fathom, you can limit the decimal points in bc’s output only in division, not multiplication. ::tears hair out::

Ktappe Thanks for your input.

scale wont work for multiplications.

You can try

echo “scale=2;57*43.1234567/1” | bc

it should work.

Bash divide floating numbers

https://viewsby.wordpress.com/2013/09/04/bash-divide-floating-numbers/