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

标签 json go

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

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

下面是我正在做的事情的一个真正浓缩的要点。在将 supply 编码为 json 之前,我对它的值进行了更多修改。

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/

相关文章:

android - 如何在主页按钮上单击退出应用程序?

java - POSTed JSON 中的实体关系与 Spring Boot

javascript - 如何使用类似 JSON 的 JQuery 函数?

windows - 使用 lxn/win 在 golang 中处理 LPTSTR

go - 将字节数组传递给插件函数

iphone - 复杂的 JSON 作为 UITableView iOS 的 NSArray 数据源

android - 从 JSONArray 转换为 ArrayList<CustomObject> - Android

戈朗 : Is a network condition can make a net/http HandleFunc to panic?

go - 获取 websocket session

GoLang,把资源放回 channel 挂我的程序