golang 浮点类型数据精度损失问题的解决方案

float 精度丢失的原因可参考下贴:

 

https://blog.csdn.net/mario08/article/details/90170142

处理精度的几种方法:

1: float 转 decimal 类型,decimal 互乘 不会丢失精度

2: float 乘 float 后,进行四舍五入  只保留需要的位数

	var refundFee, _ = strconv.ParseFloat("1129.6", 64)
	log.Println(refundFee) //1129.6   float类型
	f1 := decimal.NewFromFloat(refundFee)  
	log.Println(f1)  //1129.6  decimal 类型
	f2 := decimal.NewFromFloat(100)
	log.Println(f1.Mul(f2)) // 112960 decimal 类型

	log.Println(refundFee * 100) //112959.99999999999 
	

	var s = Round(refundFee*100, 2)
	log.Println(s)     // 112960

// f:需要处理的浮点数,n:要保留小数的位数
// Pow10()返回10的n次方,最后一位四舍五入,对n+1位加0.5后四舍五入
func Round(f float64, n int) float64 {
	n10 := math.Pow10(n)
	return math.Trunc((f+0.5/n10)*n10) / n10
}

 

 

你可能感兴趣的:(go)