Search code examples
shexpr

round to 2 decimals sh


I would like to get two decimals after the dot in this expression: 7/2

#temperature equal 7
tempeture= `cat temperature`  
rate= expr $temperature/2  
echo "$rate"

I'm getting 3 and I want 3.50. thks


Solution

  • One way to round to two decimails would be to use the bc command and setting the scale variable equal to 2:

    echo "scale=2; ($temperature/2)" | bc
    

    You could also use printf like this:

    printf "%.2f" $(($temperature/2))