yushizhao
yushizhao

Reputation: 751

Golang encode float to JSON with specified precision

We can print a float number with specified precision like this:

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

Can we do the same when encode float to JSON?

So that for num = 0.1234,

we can get {"num": 0.12} instead of {"num": 0.1234} .

Upvotes: 0

Views: 4083

Answers (2)

torek
torek

Reputation: 488183

Use a custom type with a custom marshal function. You may want to implement a custom unmarshaling function as well.

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.

See also the examples in the encoding/json documentation.

Edit: strconv.FormatFloat, as in josssefaz answer, will generally be more efficient than fmt.Sprintf. Unless this is a bottleneck that shows up in profiling, you should use whichever one you find clearer.

Upvotes: 4

jossefaz
jossefaz

Reputation: 3932

You can do it with the strconv.FormatFloat method :

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
}

Output :

{"Num": 0.12}

On go playground : Click here

Upvotes: 3

Related Questions