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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With