go 保留小数若干位数

感谢

https://blog.csdn.net/sjy8207380/article/details/79013827

解决的方法

· 利用取近似值的方法解决这个问题。

(1)利用fmt.Sprintf()

func Round2(f float64, n int) float64 {
floatStr := fmt.Sprintf("%."+strconv.Itoa(n)+"f", f)
inst, _ := strconv.ParseFloat(floatStr, 64)
return inst
}
(2)利用math.Trunc()

func Round(f float64, n int) float64 {
n10 := math.Pow10(n)
return math.Trunc((f+0.5/n10)*n10) / n10
}

原文地址:https://www.cnblogs.com/zonglonglong/p/10044707.html