This is a creation in Article, where the information may have evolved or changed.
Today, we encounter a problem with the calculation of a floating point number after interception. After the interception of floating-point numbers, and then operation, will result in inaccurate accuracy. This is not necessary, but is determined by the specific floating-point number you are calculating. You have to find a way 100% to avoid this problem.
Go directly to the code.
Problem code
package mainimport ("fmt""strconv")func main() {var ff, e float64e = 100.00ff = -0.210615789ff = FloatRound(ff, 4)fmt.Println(ff) // 输出 -0.2106qq := ff * efmt.Println(qq) // 输出 -21.060000000000002}// 截取小数位数func FloatRound(f float64, n int) float64 {format := "%." + strconv.Itoa(n) + "f"res, _ := strconv.ParseFloat(fmt.Sprintf(format, f), 64)return res}
Can see the output of QQ, not we think that is-21.06.
Therefore, the subsequent interception of floating-point numbers must be placed after the operation. The correct code is as follows
package mainimport ("fmt""strconv")func main() {var ff, e float64e = 100.00ff = -0.210615789 // 先计算qq := ff * efmt.Println(qq) // 输出 -21.0615789 // 再截取qq = FloatRound(qq, 4)fmt.Println(qq) // 输出 -21.0616}// 截取小数位数func FloatRound(f float64, n int) float64 {format := "%." + strconv.Itoa(n) + "f"res, _ := strconv.ParseFloat(fmt.Sprintf(format, f), 64)return res}