How to round decimals using bc in bash?
A quick example of what I want using bash scripting:
#!/bin/bash
echo "Insert the price you want to calculate:"
read float
echo "This is the price without taxes:"
echo "scale=2; $float/1.18" |bc -l
read -p "Press any key to continue..."
bash scriptname.sh
Assuming that the price is: 48.86
The answer will be:41.406779661 (41.40 actually because I'm using scale=2;
)
My Question is: How I round the second decimal to show the answer in this way?: 41.41
Solution 1:
Simplest solution:
printf %.2f $(echo "$float/1.18" | bc -l)
Solution 2:
A bash round function:
round()
{
echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1)+0.5)/(10^$2)" | bc))
};
Used in your code example:
#!/bin/bash
# the function "round()" was taken from
# http://stempell.com/2009/08/rechnen-in-bash/
# the round function:
round()
{
echo $(printf %.$2f $(echo "scale=$2;(((10^$2)*$1)+0.5)/(10^$2)" | bc))
};
echo "Insert the price you want to calculate:"
read float
echo "This is the price without taxes:"
#echo "scale=2; $float/1.18" |bc -l
echo $(round $float/1.18 2);
read -p "Press any key to continue..."
Good luck :o)
Solution 3:
Bash/awk rounding:
echo "23.49" | awk '{printf("%d\n",$1 + 0.5)}'
If you have python you can use something like this:
echo "4.678923" | python -c "print round(float(raw_input()))"
Solution 4:
Here's a purely bc solution. Rounding rules: at +/- 0.5, round away from zero.
Put the scale you're looking for in $result_scale; your math should be where $MATH is located in the bc command list:
bc <<MATH
h=0
scale=0
/* the magnitude of the result scale */
t=(10 ^ $result_scale)
/* work with an extra digit */
scale=$result_scale + 1
/* your math into var: m */
m=($MATH)
/* rounding and output */
if (m < 0) h=-0.5
if (m > 0) h=0.5
a=(m * t + h)
scale=$result_scale
a / t
MATH