Golang floating point accuracy problem

Source: Internet
Author: User
Tags sprintf
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}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.