dushaoshuai / dushaoshuai.github.io

https://www.shuai.host
0 stars 0 forks source link

Go :: 格式化浮点数,保留 n 位小数 #39

Open dushaoshuai opened 1 year ago

dushaoshuai commented 1 year ago

round to nearest

func RoundPrecision(x float64, precision int) float64 {
    ratio := math.Pow10(precision)
    return math.Round(x*ratio) / ratio
}

round up

func RoundUpPrecision(x float64, precision int) float64 {
    ratio := math.Pow10(precision)
    return math.Ceil(x*ratio) / ratio
}

round down

func RoundDownPrecision(x float64, precision int) float64 {
    ratio := math.Pow10(precision)
    return math.Floor(x*ratio) / ratio
}