Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash calculation using bc, and round up floating point

Tags:

bash

shell

Sorry for my bad title. I'm so confuse to explain the title in 1 line. this is my problem:

echo "scale=0;9 * 150 + 8.092 * 560 + 3.181" | bc

instead of getting

5885

but, i got output

5884.701

Anyone?

like image 543
Jamz D. Mozac Avatar asked Sep 26 '15 12:09

Jamz D. Mozac


People also ask

How do I round a float in Bash?

The format string “%. 0f” sets the float precision to 0. That is, it only keeps the integer part. Also, printf will round to the nearest integer.

How do I use floating point numbers in Bash?

While you can't use floating point division in Bash you can use fixed point division. All that you need to do is multiply your integers by a power of 10 and then divide off the integer part and use a modulo operation to get the fractional part. Rounding as needed.

Does Bash support floating point?

2. Bash arithmetic expansion does not support floating-point arithmetic. When attempting to divide in this case, the output shows zero (0). The result of integer division must be an integer.


1 Answers

As far as I know only division is using the information given by scale.

echo "scale=0; (9 * 150 + 8.092 * 560 + 3.181)/1" | bc

will echo 5884 since the integer part (quotient!) was taken only. To get your desired result (round) you might use:

echo "scale=0; ((9 * 150 + 8.092 * 560 + 3.181)+0.5)/1" | bc

note that this approach will not work for negative numbers! See this post: https://unix.stackexchange.com/a/89843

like image 99
fjellfly Avatar answered Sep 28 '22 15:09

fjellfly