时间:2021-07-22 07:46:29 | 栏目:Golang | 点击:次
比如乘法运算,实例,将小数的元转换成整数的分:
发现将小数的元乘以100后强制转换为整数分,少了1分
var ( a, b float64 c int64 ) a = 2.55 b = 0.0
c = int64((a + b) * 100.0) fmt.Printf("第1次 c=%d\n", c) //第1次 c=254 c = int64(a * 100.0) fmt.Printf("第2次 c=%d\n", c) //第2次 c=254 fmt.Println(a * 100) //254.99999999999997 //发现将小数的元乘以100后强制转换为整数分,少了1分 //解决办发1: tmpStr1 := fmt.Sprintf("%.2f", a) tmpStr2 := fmt.Sprintf("%.2f", b) tmpnum1, _ := strconv.ParseInt(strings.Replace(tmpStr1, ".", "", 1), 10, 64) tmpnum2, _ := strconv.ParseInt(strings.Replace(tmpStr2, ".", "", 1), 10, 64) c = tmpnum1 + tmpnum2 fmt.Printf("第3次 c=%d\n", c) //第3次 c=255
//方法2:
num3 := math.Ceil(a * 100.0) fmt.Printf(“num3=%d\n”, int64(num3)) //num3=255 //方法3: strFloat := strconv.FormatFloat(a*100, ‘f', 0, 64) nInt64, err := strconv.ParseInt(strFloat, 10, 64)
补充:golang float64,in64相互转换精度控制
//将float64转成精确的int64 func Wrap(num float64, retain int) int64 { return int64(num * math.Pow10(retain)) } //将int64恢复成正常的float64 func Unwrap(num int64, retain int) float64 { return float64(num) / math.Pow10(retain) } //精准float64 func WrapToFloat64(num float64, retain int) float64 { return num * math.Pow10(retain) } //精准int64 func UnwrapToInt64(num int64, retain int) int64 { return int64(Unwrap(num, retain)) }