Home > Backend Development > Golang > How Can I Preserve Trailing Zeros When Marshaling Floats to JSON in Go?

How Can I Preserve Trailing Zeros When Marshaling Floats to JSON in Go?

Susan Sarandon
Release: 2024-11-28 08:21:12
Original
489 people have browsed it

How Can I Preserve Trailing Zeros When Marshaling Floats to JSON in Go?

JSON Marshal and Float Trailing Zeros

Problem:

When marshaling float numbers to JSON using json.Marshal(), the trailing zeros are stripped, potentially causing issues when parsing the JSON with external programs.

Solution:

To preserve the trailing zeros in the JSON output, one approach is to define a custom float type and provide a custom MarshalJSON() method for it.

type KeepZero float64

func (f KeepZero) MarshalJSON() ([]byte, error) {
    if float64(f) == float64(int(f)) {
        return []byte(strconv.FormatFloat(float64(f), 'f', 1, 32)), nil
    }
    return []byte(strconv.FormatFloat(float64(f), 'f', -1, 32)), nil
}
Copy after login

In this implementation:

  • The KeepZero type wraps the float64 type.
  • The MarshalJSON() method checks if the float is an integer (with no decimal part). If so, it uses the strconv.FormatFloat() function with a precision of 1 decimal place to ensure the trailing zero is retained.
  • Otherwise, it uses a precision of -1 to avoid specifying a fixed number of decimal places.

Example:

type Pt struct {
    Value KeepZero
    Unit  string
}

func main() {
    data, err := json.Marshal(Pt{40.0, "some_string"})
    fmt.Println(string(data), err)
}
Copy after login

This example will produce the desired JSON output:

{"Value":40.0,"Unit":"some_string"}
Copy after login

The above is the detailed content of How Can I Preserve Trailing Zeros When Marshaling Floats to JSON in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template