0
点赞
收藏
分享

微信扫一扫

go 保留小数若干位数

飞进科技 2022-06-01 阅读 57

 

解决的方法

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

(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
}

 

破罐子互摔


举报

相关推荐

0 条评论