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 }
In this implementation:
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!