2

Bash returns value 4 instead of 4.2 when dividing 21/5. And returns 36 when doing 9 * (21/5) instead of 37.8.

echo "$(( 21/5 ))"
4
    
echo "21/5" | bc
4

Similarly 9 * ( 21/5 ) returns 36 but it should be 37.8;

y = 9;
num_lines = 21;
w = 5;

let value="$y * ($num_lines/$w)"

echo $value
36
davide-pi
  • 127
  • 7
Robert
  • 23
  • 2
  • 1
    Bash's arithmetic expansion does not support floating-point calculations. Look at [this question](https://unix.stackexchange.com/q/40786/381289) for other possibilities. – Piotr P. Karwasz Mar 28 '20 at 11:21

1 Answers1

3

try something like this

$ echo "21/5" | bc -l
4.20000000000000000000

$ echo "$y * ($num_lines/$w)" |bc -l
37.80000000000000000000

For setting up limit of decimal point use like below, For 2 decimal point

 $echo "scale=2; $y * ($num_lines/$w)" | bc -l
 37.80

For 3 decimal point, just change the scale number.

$ echo "scale=3; $y * ($num_lines/$w)" | bc -l
37.800
asktyagi
  • 2,860
  • 2
  • 8
  • 25