登录
首页 >  Golang >  Go问答

使用 Golang 将浮点数编码为 JSON,并指定精度

来源:stackoverflow

时间:2024-02-22 14:45:26 443浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《使用 Golang 将浮点数编码为 JSON,并指定精度》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我们可以像这样打印指定精度的浮点数:

fmt.Printf("%.2f", num)

将 float 编码为 JSON 时我们可以做同样的事情吗?

因此对于 num = 0.1234,

我们可以得到 {"num": 0.12} 而不是 {"num": 0.1234} 。


解决方案


使用带有自定义编组函数的自定义类型。您可能还想实现自定义解组函数。

type lpfloat struct {
    value  float32 // the actual value
    digits int     // the number of digits used in json
}

func (l lpfloat) marshaljson() ([]byte, error) {
    s := fmt.sprintf("%.*f", l.digits, l.value)
    return []byte(s), nil
}

Here is a working example on the Go playground

另请参阅 encoding/json documentation 中的示例。

编辑:strconv.formatfloat(如 josssefaz answer 所示)通常比 fmt.sprintf 更有效。除非这是分析中出现的瓶颈,否则您应该使用您认为更清晰的那个。

您可以使用 strconv.formatfloat 方法来完成此操作:

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)


type RoundedFloat float64

type RoundIt struct {
    Num RoundedFloat
}


func main() {
    data, _:= json.Marshal(RoundIt{ 0.1234})
    fmt.Println(string(data))
}
#Implement your own MarshalJSON func
func (r RoundedFloat) MarshalJSON() ([]byte, error) {
        return []byte(strconv.FormatFloat(float64(r), 'f', 2, 32)), nil
}

输出:

{"num": 0.12}

on go 演示:Click here

以上就是《使用 Golang 将浮点数编码为 JSON,并指定精度》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>