bc: set number of digits after decimal point

Solution 1:

Set the scale special variable:

$ echo "scale=2; 100/3" | bc
33.33

Solution 2:

scale works only for division; if some geeks need it in multiplication, then you can do achieve this by using string manipulation. Say if you need to multiply 32 * 0.60 , answer is 19.20. If you need to get it 19 alone in answer you can get it by different methods.

  1. Using String Manipulation

    $ S=$(echo "32*.60" | bc ) ; echo ${S%.*}
    19
    

    String Manipulation syntax: ${Variable%pattern}, this will delete short matching pattern that comes after %. For more String manipulation details see the Advanced Bash-Scripting Guide.

  2. Using Scale as stated by **chronitis**

    $ echo "scale=0; 32*60/100" | bc
    19
    
  3. To get rid of the trailing 0s, instead of string manipulation, one can also do a divide by 1.

    $ echo "0.232 * 1000" | bc
    232.000
    
    $ echo "0.232 * 1000 / 1" | bc
    232
    

Solution 3:

In addition to previous answers

echo "scale=2; 1.0150876" | bc

Returns

1.0150876

Add Math operations to get only 2 decimal numbers - (NUMBER*100)/100

echo "scale=2; (1.0150876 * 100) / 100" | bc

Now returns

1.01

Solution 4:

you can also use printf command to round off result upto 3 decimals

# printf "%.3f\n" $(echo "100/3" | bc -l)
3.333