Skip to content

encoding/json: encode precise floating point integers using %.0f, not %g #6384

@joeshaw

Description

@joeshaw
Go 1.1.2 on OS X 10.8.4, and on play.golang.org.

If you unmarshal a JSON numeric value into interface{}, it is encoded as a float64.  If
it is sufficiently large (>= 1e6, I believe) when you marshal it, it is encoded as a
string using exponent notation.  If the original value was an integer and you later try
to decode into an int64 value, an error is returned.

Example code is available here: http://play.golang.org/p/fYuB4tT7Ul

Using 'f' for the fmt byte to AppendFloat() instead of 'g' in
http://golang.org/src/pkg/encoding/json/encode.go#L334 would solve this problem, as
values which can be represented as integers will be encoded in a way that can be read
back in as integers.

(There are other issues as you get to very large values, since float64 can't encode a
whole int64... not sure what or if anything can be done about that.)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions