如何在 Go 中获取精确的 float64 值?

tru*_*ans -1 floating-point precision go

我得到一个float64值43701.330694444441,在我调用strconv.ParseFloat(v, 64)函数后,结果是43701.33069444444。任何人都可以解决这个问题吗?

v := "43701.330694444441"

f, err := strconv.ParseFloat(v, 64)
if err != nil {
    return
}
fmt.Println(f) // it output 43701.33069444444, the tail '1' is missing.
Run Code Online (Sandbox Code Playgroud)

pet*_*rSO 5

float6453 位精度64 位 IEEE 754 二进制浮点的局限性。为了获得更精确的表示,请使用更精确的math/big类型。Float

例如,

package main

import (
    "fmt"
    "math/big"
    "strconv"
)

func main() {
    v := "43701.330694444441"
    f1, err := strconv.ParseFloat(v, 64) // 53-bit precision
    fmt.Println(f1, err)
    f2, ok := big.NewFloat(0).SetPrec(53).SetString(v)
    fmt.Println(f2, ok)
    f3, ok := big.NewFloat(0).SetPrec(55).SetString(v)
    fmt.Println(f3, ok)
}
Run Code Online (Sandbox Code Playgroud)

游乐场:https://play.golang.org/p/8aVj-y83Mdp

输出:

43701.33069444444 <nil>
43701.33069444444 true
43701.330694444441 true
Run Code Online (Sandbox Code Playgroud)