Skip to content

Commit

Permalink
lib/json: encode floating point numbers with a decimal point (#564)
Browse files Browse the repository at this point in the history
The previous code carelessly used Go's %g operator
when it should have used Starlark's.

Fixes #563
  • Loading branch information
adonovan authored Nov 19, 2024
1 parent 1207426 commit d4d7611
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
3 changes: 2 additions & 1 deletion lib/json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ func encode(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, k
if !isFinite(float64(x)) {
return fmt.Errorf("cannot encode non-finite float %v", x)
}
fmt.Fprintf(buf, "%g", x) // always contains a decimal point
// Float.String always contains a decimal point. (%g does not!)
buf.WriteString(x.String())

case starlark.String:
quote(string(x))
Expand Down
7 changes: 6 additions & 1 deletion starlark/testdata/json.star
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,13 @@ numbers = [
0, 1, -1, +1, 1.23e45, -1.23e-45,
3539537889086624823140625,
float(3539537889086624823140625),
float(1.0),
]
assert.eq(codec(numbers), numbers)
def number_roundtrip():
show = lambda n: (n, type(n))
for n in numbers:
assert.eq(show(codec(n)), show(n)) # ensure no int/float confusion
number_roundtrip()

## json.indent

Expand Down

0 comments on commit d4d7611

Please sign in to comment.