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

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-24 06:12:10932browse

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

Preserve Trailing Zeros in JSON Marshaled Floating-Point Numbers

In Go, the json.Marshal() function often strips trailing zeros from floating-point numbers during marshalling. This can lead to loss of precision in certain scenarios.

Problem:

When marshalling a Go program's value with a trailing zero (e.g., 40.0), json.Marshal() outputs the value without the zero (e.g., 40). This behavior can be problematic if external programs expect floating-point numbers with trailing zeros.

Solution 1 (Recommended): Use a Custom Float Type

Define a custom float type and implement the MarshalJSON() method to control the JSON serialization. Here's an example:

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 custom type, the MarshalJSON() method converts the float to a string with one decimal place (if it's a whole number) or preserves all decimal places (if it's not a whole number).

Example:

type Pt struct {
    Value KeepZero
    Unit  string
}

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

This code outputs {"Value":40.0,"Unit":"some_string"} , preserving the trailing zero in the JSON output.

The above is the detailed content of How to Preserve Trailing Zeros When Marshaling Floats in Go JSON?. 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