json - 将数字从 float64 转换为 Int64 不正确

标签 json string go floating-point precision

关闭。这个问题是not reproducible or was caused by typos .它目前不接受答案。












想改进这个问题?将问题更新为 on-topic对于堆栈溢出。

2年前关闭。




Improve this question




我尝试写一个函数,代码:

package main

import (
    "encoding/json"
    "fmt"
)

type Test struct {
    Data map[string]interface{} `json:"data"`
}

func main() {
    jsonStr := "{\"data\": {\"id\": 999804707614896129}}"
    t := &Test{}
    json.Unmarshal([]byte(jsonStr), t)
    fmt.Println(int64(t.Data["id"].(float64)))
    var x float64 = 999804707614896129
    fmt.Println(int64(x))
}


结果如下:
999804707614896128
999804707614896128

为什么结果是 999804707614896128,而不是 999804707614896129。

最佳答案

因为999804707614896129不能用 float64 类型的值精确表示. float64使用 IEEE 754表示浮点数的标准。这是一种精度有限的格式(大约 16 个十进制数字)。

如果您需要“传输”确切的数字,请使用字符串而不是 JSON 数字。如果数字“适合”int64 ,您将能够“准确地”解析它(否则只需将其用作 string 或使用 big.Int ):

jsonStr := `{"data": {"id": "999804707614896129"}}`
t := &Test{}
if err := json.Unmarshal([]byte(jsonStr), t); err != nil {
    panic(err)
}

s := t.Data["id"].(string)
fmt.Println(s)
var x int64
x, err := strconv.ParseInt(s, 10, 64)
fmt.Println(x, err)

这将输出(在 Go Playground 上尝试):
999804707614896129
999804707614896129 <nil>

关于json - 将数字从 float64 转换为 Int64 不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59716314/

相关文章:

json - 使用 NSJSONSerialization 从 json 响应构建对象

C str 函数和 malloc

ssl - 尝试使用 TLS 连接到 LDAP 时出错 'LDAP Result Code 201 "ErrorNetwork": Invalid packet format'

javascript - 应用 JSON.parse 后包含\"的 JSON 字符串

javascript - 多维数组和 jQuery 的 getJSON

java - JAX-RS 和 Jersey : Properly Nested JSON

c - 当你有字符串和双变量时如何扫描

android - 如何获得仅包含POST响应的最后一部分的字符串?

go - impl函数的参数不足

inheritance - 转到 : can assign struct to an interface, 但不是上层结构