How to round decimals using bc in bash?

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)


Simplest solution:

printf %.2f $(echo "$float/1.18" | bc -l)

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()))"

Tags:

Bash

Bc

Scripts