Stop json.Marshal() from stripping trailing zero from floating point number

后端 未结 5 510
梦谈多话
梦谈多话 2020-12-21 01:04

I got the following problem: My golang program converts some information into JSON. For example it results in the following json:

{
   \"value\":40,
   \"uni         


        
5条回答
  •  攒了一身酷
    2020-12-21 01:31

    By default floating point numbers are rendered without a decimal point and fractions if its value is an integer value. The representation is shorter, and it means the same number.

    If you want control over how a number appears in the JSON representation, use the json.Number type.

    Example:

    type Pt struct {
        Value json.Number
        Unit  string
    }
    
    func main() {
        data, err := json.Marshal(Pt{json.Number("40.0"), "some_string"})
        fmt.Println(string(data), err)
    }
    

    Output (try it on the Go Playground):

    {"Value":40.0,"Unit":"some_string"} 
    

    If you have a number as a float64 value, you may convert it to json.Number like this:

    func toNumber(f float64) json.Number {
        var s string
        if f == float64(int64(f)) {
            s = fmt.Sprintf("%.1f", f) // 1 decimal if integer
        } else {
            s = fmt.Sprint(f)
        }
        return json.Number(s)
    }
    

    Testing it:

    f := 40.0
    data, err := json.Marshal(Pt{toNumber(f), "some_string"})
    fmt.Println(string(data), err)
    
    f = 40.123
    data, err = json.Marshal(Pt{toNumber(f), "some_string"})
    fmt.Println(string(data), err)
    

    Output (try it on the Go Playground):

    {"Value":40.0,"Unit":"some_string"} 
    {"Value":40.123,"Unit":"some_string"} 
    

    The other direction, if you want the float64 value of a json.Number, simply call its Number.Float64() method.

提交回复
热议问题