【问题标题】:Golang math/big Unmarshal Lost PrecisionGolang 数学/大 Unmarshal 丢失精度
【发布时间】:2016-05-02 03:41:08
【问题描述】:

我有一个类似的结构:

type Msg struct {
    F1  *big.Float `json:"F1,string"`
}

然后我从消息队列中收到json 中的一条消息,然后我想将该 json 消息解组到我的 Msg 结构中:

// jsonMsg = {"F1": "1000314.451234"}
var msg Msg
json.Unmarshal(jsonMsg, &msg)

但我得到了:

fmt.Println("go object:",msg.F1.String()) // 1000314.45, precision lost

因此,当我的字符串 "1000314.451234" 解组为 golang 中的 Msg 对象时,精度会丢失。我想知道这是否是错误?我怎样才能获得完整的精度?谢谢。

【问题讨论】:

    标签: go bigdecimal unmarshalling


    【解决方案1】:

    解组时不会丢失精度。当您将 Float 转换为 String 进行打印时,它会“丢失”。

    package main
    
    import (
        "fmt"
        "encoding/json"
        "math/big"
    )
    
    type Msg struct {
        F1  *big.Float `json:"F1,string"`
    }
    
    func main() {
        jsonMsg := []byte(`{"F1": "1000314.451234"}`)
        var msg Msg
        json.Unmarshal(jsonMsg, &msg)
        fmt.Println("go object:",msg.F1.String())
        fmt.Printf("go object: %f", msg.F1)
    }
    

    这个测试的输出将是:

    go object: 1000314.451
    go object: 1000314.451234
    

    所以只取决于您如何打印数据。 戈多克fmt printing

    【讨论】:

    • 是的。这是因为默认情况下,字符串函数使用 msg.Text('g', 10) 所以看起来精度已经丢失。当 "fmt.Println("go object:", msg.F1.Text('f', 6))" 时,可以看到没有丢失。我也正要发布同样的东西,但你打败了我。
    猜你喜欢
    • 2013-06-17
    • 2014-09-18
    • 2012-05-13
    • 2013-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多