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
Susan SarandonOriginal
2024-11-28 08:21:12488browse

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
}

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)
}

This example will produce the desired JSON output:

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

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!

Statement:
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