Home >Backend Development >Golang >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:
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!