Convert number from float64 to Int64 is incorrect [closed]

折月煮酒 提交于 2020-01-30 13:27:09

问题


I try to write a function, the code:

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

The result is below:

999804707614896128
999804707614896128

Why the results are 999804707614896128, not 999804707614896129.


回答1:


Because 999804707614896129 cannot be represented exactly with a value of type float64. float64 uses the IEEE 754 standard for representing floating point numbers. It's a format with limited precision (roughly 16 decimal digits).

If you need to "transfer" the exact number, use string and not JSON number. If the number "fits" into an int64, you will be able to parse it "exactly" (else just work with it as a string or use 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)

This will output (try it on the Go Playground):

999804707614896129
999804707614896129 <nil>


来源:https://stackoverflow.com/questions/59716314/convert-number-from-float64-to-int64-is-incorrect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!