Skip to content

Commit

Permalink
lib/json: encode floating point numbers with a decimal point
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 committed Nov 19, 2024
1 parent 1207426 commit 947be58
Show file tree
Hide file tree
Showing 2 changed files with 9 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
8 changes: 7 additions & 1 deletion starlark/testdata/json.star
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,14 @@ numbers = [
0, 1, -1, +1, 1.23e45, -1.23e-45,
3539537889086624823140625,
float(3539537889086624823140625),
float(1.0),
]
assert.eq(codec(numbers), numbers)
def number_roundtrip():
for n in numbers:
n2 = codec(n)
assert.eq(n2, n)
assert.eq(type(n2), type(n)) # ensure no int/float confusion
number_roundtrip()

## json.indent

Expand Down

0 comments on commit 947be58

Please sign in to comment.