Stop json.Marshal() from stripping trailing zero from floating point number

后端 未结 5 514
梦谈多话
梦谈多话 2020-12-21 01:04

I got the following problem: My golang program converts some information into JSON. For example it results in the following json:

{
   \"value\":40,
   \"uni         


        
5条回答
  •  借酒劲吻你
    2020-12-21 01:35

      type MyFloat float64
      func (mf MyFloat) MarshalJSON() ([]byte, error) {                                                          
          return []byte(fmt.Sprintf("%.1f", float64(mf))), nil                                                     
      }
    

    used like this

     type PricePoint struct {
         Price    MyFloat   `json:"price"`
         From     time.Time `json:"valid_from"`
         To       time.Time `json:"valid_to"`
     }
    

    Replace the 1 in "%.1f" with what ever precision you need

提交回复
热议问题