Rounding Numbers with bc in Bash

后端 未结 3 656
無奈伤痛
無奈伤痛 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条回答
  •  感情败类
    2021-01-02 05:15

    Next function round argument 'x' to 'd' digits:

    define r(x, d) {
        auto r, s
    
        if(0 > x) {
            return -r(-x, d)
        }
        r = x + 0.5*10^-d
        s = scale
        scale = d
        r = r*10/10
        scale = s  
        return r
    } 
    

提交回复
热议问题