Golang json.Marshal() com ponto flutuante

Com o GO quando uma struct tem um atributo do type float64 e seu valor é 40.0 o return JSON fica com o valor 40.

Como fica:

{
"valor": 40
}

Como queremos:

{
"valor": 40.0
}

Para conseguirmos isso precisamos reimplementar json.Marshal().

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
}

type Pt struct {
Value KeepZero
}

func main() {
data, err := json.Marshal(Pt{40.0})
fmt.Println(string(data), err)
}

Espero ter ajudado. Até mais!

--

--