关闭。这个问题是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/