問題: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