Home > Backend Development > Golang > How Can I Preserve Floating-Point Precision When Marshaling JSON in Go?

How Can I Preserve Floating-Point Precision When Marshaling JSON in Go?

Susan Sarandon
Release: 2024-11-29 19:20:12
Original
1043 people have browsed it

How Can I Preserve Floating-Point Precision When Marshaling JSON in Go?

Preserving Floating Point Precision in JSON Marshaling

In Go, the json.Marshal() function often removes trailing zeros from floating-point numbers during JSON serialization. This can be problematic if the consuming application requires the full precision of the original value.

To overcome this issue, consider defining a custom data type that encapsulates the floating-point value. Here's an example:

type PreservedFloat float64

func (f PreservedFloat) MarshalJSON() ([]byte, error) {
    // Preserve trailing zeros in the JSON representation.
    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 PreservedFloat type serves as a wrapper around a standard float64.
  • The MarshalJSON method overrides the default JSON serialization behavior.
  • If the value has an integer representation (no fractional part), it is formatted with one decimal place to preserve the trailing zero.
  • Otherwise, the value is formatted without specifying a precision, allowing it to retain its full accuracy.

By using PreservedFloat, you can control the JSON representation of your floating-point values, ensuring that they retain their precision even after marshaling.

The above is the detailed content of How Can I Preserve Floating-Point Precision When Marshaling 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