2
#! /bin/sh
a1=260
a2=9150
echo "$a1 * 100 / $a2" | bc

the output is

2

where it should be

2.8415

why is precision lost although I'm using bc?

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
A K
  • 737
  • 2
  • 8
  • 17

3 Answers3

7

Try this (easy to re-use, you just need to remember to prepends the math expression with scale=N) :

$ echo "scale=10; $a1 * 100 / $a2" | bc
2.8415300546

As you can see, you can specify the scale length like you want.

See

man bc | less +/^' *scale \(\s*exp
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
4

You can load the math library: bc -l

#! /bin/sh
a1=260
a2=9150
echo "$a1 * 100 / $a2" | bc -l

the output is

2.84153005464480874316
Edoot
  • 391
  • 1
  • 4
0

You can use awk for better arithmetic:

awk -v a1=260 -v a2=9150 'BEGIN{printf("%.4f\n", (a1 * 100 / a2))}' 

output: 2.8415

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 3
    in what way is it better it looks more complicated – user568109 Apr 03 '13 at 17:45
  • @user568109: I just meant awk provides better arithmetic capabilities than standard bash btw which part is looking complicated to you? – anubhava Apr 03 '13 at 17:58
  • 1
    you can do it with bc easily and OP did not ask for awk – user568109 Apr 03 '13 at 18:01
  • `bc` is designed especially for math, I don't see any relevant point where `awk` will be better, and moreover, he uses already `bc` – Gilles Quénot Apr 03 '13 at 18:01
  • @user568109 Where exactly did I say that `awk is better than bc` I just presented another option to perform floating point arithmetic not available in standard bash (bc is a an external tool as well). – anubhava Apr 03 '13 at 18:04