In bash script, I have 1 script like this:
n1 = 1
n0 = 59
# compute p1
p1=$((n1/n0))
echo "p1 = $p1"
I'd like my output is p1 = 1/59 = 0.016949153 but reality, output is p1 = 0
So, How to fix it. help me please
In bash script, I have 1 script like this:
n1 = 1
n0 = 59
# compute p1
p1=$((n1/n0))
echo "p1 = $p1"
I'd like my output is p1 = 1/59 = 0.016949153 but reality, output is p1 = 0
So, How to fix it. help me please
BASH doesn't do any floating point maths. You can either use bc
or awk
for that.
For ex::
p1=$(bc -l <<< "scale=5; $n1/$n0")
echo "$p1"
.01694
UPDATE: Using awk:
awk -v n1=$n1 -v n0=$n0 'BEGIN{printf("%.5f\n", (n1/n0))}'
0.01695
You can use bc
to get arbitrary precision maths:
pax> n1=355 ; n0=113
pax> p1=$(echo "scale=50;$n1/$n0" | BC_LINE_LENGTH=9999 bc) ; echo $p1
3.14159292035398230088495575221238938053097345132743
The line length stops bc
from doing its annoying line break behaviour for longer results.
If you have a more reverse polish mindset like me, you can also use dc
:
pax> n1=355 ; n0=113
pax> echo 50 k $n1 $n0 / p | dc
3.14159292035398230088495575221238938053097345132743
In both cases, you can set the scale to be used (by setting scale
in bc
or using the k
command in dc
).