Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash and bc math calculation with decimal point

I am trying to implement the following calculation within a Bash script using "bc" but the "scale" option is producing an incorrect result with 2 additional zeros at the end, which means that I am having to trim it manually (ugly).

Calculation:

((2592000-239)÷2592000)×100

Expected result: 99,990779321 (But I would like to show only 2 decimal places)

In Bash:

echo "scale=2; ((2592000-239)/2592000)*100" | bc

99.00

echo "scale=3; ((2592000-239)/2592000)*100" | bc

99.900

echo "scale=4; ((2592000-239)/2592000)*100" | bc

99.9900

echo "scale=5; ((2592000-239)/2592000)*100" | bc

99.99000

echo "scale=8; ((2592000-239)/2592000)*100" | bc

echo "scale=8; ((2592000-239)/2592000)*100" | bc

99.99077900

echo "scale=10; ((2592000-239)/2592000)*100" | bc

99.9907793200

According to the man page:

NUMBERS The most basic element in bc is the number. Numbers are arbitrary precision numbers. This precision is both in the integer part and the fractional part. All numbers are represented internally in decimal and all computation is done in decimal. (This version truncates results from divide and multiply operations.) There are two attributes of numbers, the length and the scale. The length is the total number of significant decimal digits in a number and the scale is the total number of decimal digits after the decimal point. For example: .000001 has a length of 6 and scale of 6. 1935.000 has a length of 7 and a scale of 3.

Am I understand this correctly?

like image 224
Arturski Avatar asked Oct 27 '25 12:10

Arturski


2 Answers

You can use:

echo 'scale=2; 100*(2592000-239)/2592000' | bc -l

99.99

You're getting 99.00 because you're dividing first that gets .99 and when it is multiplied with 100 it becomes 99.00 (due to scale-2)

like image 147
anubhava Avatar answered Oct 30 '25 05:10

anubhava


If you don't want check your bc statements for the correct math-operations order, (the scale is applied for division) just let calculate bc using the default precision a format the output in bash, like:

printf "%.2f\n" $( bc -l <<< '((2592000-239)/2592000)*100' )
# 99.99
like image 24
jm666 Avatar answered Oct 30 '25 05:10

jm666