JSON 序列化保持固定精度
type LPFloat struct {
Value float32 // the actual value
Digits int // the number of digits used in json
}
func (l LPFloat) MarshalJSON() ([]byte, error) {
s := fmt.Sprintf("%.*f", l.Digits, l.Value)
return []byte(s), nil
}
type T struct {
FamilyName string `json:"name"`
Children LPFloat `json:"kids"`
}
func main {
b, err := json.Marshal(T{"Flintstone", LPFloat{Value: 2.493, Digits: 6}})
if err != nil {
panic(err)
}
fmt.Println(string(b))
}