golang踩坑之floa64精度丢失

问题:19.90转为float64类型,再乘以100,精度丢失

废话不说多,show you the code

package main

import (
	"fmt"
	"strconv"
)

func main() {
	num, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", 19.90), 64)
	fmt.Println(num)
	fmt.Println(num * 100)
}

运行输出

19.9
1989.9999999999998

19.9转成float64后,再乘以100,居然变成了1989.9999999999998
这个精度的问题要是出现在现金的问题上就厉害了!

解决

使用包的decimal类型:github.com/shopspring/decimal

代码改为如下

package main

import (
	"fmt"
	"github.com/shopspring/decimal"
	"strconv"
)

func main() {
	num, _ := strconv.ParseFloat(fmt.Sprintf("%.8f", 19.90), 64)
	fmt.Println(num)

	decimalValue := decimal.NewFromFloat(num)
	decimalValue = decimalValue.Mul(decimal.NewFromInt(100))

	res,_ := decimalValue.Float64()
	fmt.Println(res)
}

运行输出

19.9
1990
原文地址:https://www.cnblogs.com/chenqionghe/p/12167693.html