dongxing1853 2016-05-02 03:41
浏览 197
已采纳

Golang数学/大元帅失去精度

I have a struct like:

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

Then I got a message in json from a message queue and then I want to unmarshal that json message into my Msg struct:

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

But I got:

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

So the precision is lost when my string "1000314.451234" is unmarshaled to a Msg object in golang. I wonder if this is bug? How can I get the full precision? Thanks.

  • 写回答

1条回答 默认 最新

  • douqianrou9079 2016-05-02 07:30
    关注

    The precision is not lost when you unmarshall. It's "lost" when you convert the Float to String to print it.

    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)
    }
    

    The output of this test will be :

    go object: 1000314.451
    go object: 1000314.451234
    

    So just depend how you print the data. Godoc fmt printing

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题