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
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM