问题
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