gpt4 book ai didi

json - 在 Go 中编码为 JSON 时如何强制采用十进制格式的 float

转载 作者:IT王子 更新时间:2023-10-29 02:02:33 27 4
gpt4 key购买 nike

我有一个 big.float ,我正在将其编码为 JSON 。然而,JSON 总是以科学计数法而不是十进制计数法最终显示 float 。我可以通过将 JSON 更改为字符串而不是数字并使用 float.Text('f') 来解决此问题,但我真的更愿意将类型保留为数字。

我正在看float.Format但我认为这不合适。

下面是我正在做的事情的真正浓缩要点。在将其编码为 json 之前,我对 supply 的值做了很多修改。

type TokenSupply struct {
TotalSupply *big.Float `json:"totalSupply, omitempty"`
}
supply := Float.NewFloat(1000000)
json.NewEncoder(w).Encode(TokenSupply{supply})

返回:

{"totalSupply":"1e+06"}

最佳答案

big.Float 在转换为 JSON 类型时被编码为字符串

https://golang.org/pkg/encoding/json/#Marshal

Marshal traverses the value v recursively. If an encountered value implements the Marshaler interface and is not a nil pointer, Marshal calls its MarshalJSON method to produce JSON. If no MarshalJSON method is present but the value implements encoding.TextMarshaler instead, Marshal calls its MarshalText method and encodes the result as a JSON string. The nil pointer exception is not strictly necessary but mimics a similar, necessary exception in the behavior of UnmarshalJSON.

https://golang.org/pkg/math/big/#Float.MarshalText

func (x *Float) MarshalText() (text []byte, err error)

你能做什么?

由于您的 float 可能超过 64 位,因此它不能很好地与必须将 JSON 值读取为数字的其他语言一起使用。我建议您将数字保留为字符串。

关于json - 在 Go 中编码为 JSON 时如何强制采用十进制格式的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47341767/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com