JSON Marshaling: Preserving Trailing Zeroes in Floating-Point Numbers
When serializing data into JSON using json.Marshal() in Go, trailing zeroes in floating-point numbers are often stripped. This can be problematic when the receiving end expects floating-point values with decimal places.
Solution: Custom Marshal Function
An effective way to prevent json.Marshal() from removing the trailing zeroes is to define a custom MarshalJSON() method for the type containing the floating-point value. This allows you to manually control the serialization process.
Consider the following example:
type MyFloat float64 func (f MyFloat) MarshalJSON() ([]byte, error) { // Check if the float is an integer (no decimal part). if math.Trunc(float64(f)) == float64(f) { // Serialize as an integer without the trailing zero. return []byte(strconv.FormatInt(int64(f), 10)), nil } // Serialize as a floating-point number with the trailing zero. return []byte(strconv.FormatFloat(float64(f), 'f', -1, 64)), nil }
In this example, the MyFloat type defines a custom MarshalJSON() method that checks if the float is an integer (no decimal part) and serializes it accordingly. For floating-point numbers, it serializes them with the trailing zero intact.
Usage:
Once you have defined the custom MarshalJSON() method, you can use it to serialize objects containing the MyFloat type. For instance:
type MyStruct struct { Value MyFloat Unit string } // Serialize MyStruct using the custom MarshalJSON method. data, err := json.Marshal(MyStruct{40.0, "some_string"})
This will result in the following JSON output:
{ "Value": 40.0, "Unit": "some_string" }
Note:
The above is the detailed content of How Can I Preserve Trailing Zeroes in Go\'s JSON Marshaling of Floating-Point Numbers?. For more information, please follow other related articles on the PHP Chinese website!