Multiplication and Division with scale using bc

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


3 comments on “Multiplication and Division with scale using bc

  1. Right, but try it with multiplication. That is, compare the outputs of:
    echo “scale=2;57/43.1234567” | bc
    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::

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s