Rounding Numbers with bc in Bash

后端 未结 3 661
無奈伤痛
無奈伤痛 2021-01-02 04:54

I want to compute an average with 3 decimal figures, rounded to nearest, using bc.

For example:

average of 3, 3 and 5 should yiel

3条回答
  •  梦毁少年i
    2021-01-02 05:25

    This solution is not that flexibile (it just converts float to int), but it can deal with negative numbers:

    e=$( echo "scale=0; (${e}+0.5)/1" | bc -l )
    if [[ "${e}" -lt 0 ]] ; then
        e=$(( e - 1 ))
    fi
    

提交回复
热议问题