Skip to content

fix: round decimals half to even on their decimal value - #28

Open
bardrop wants to merge 1 commit into
dunglas:mainfrom
bardrop-oss:fix-decimal-tie-to-even
Open

bardrop wants to merge 1 commit into
dunglas:mainfrom
bardrop-oss:fix-decimal-tie-to-even

Conversation

@bardrop

@bardrop bardrop commented Nov 20, 2026

Copy link
Copy Markdown

marshalDecimal rounds d/0.001 with math.RoundToEven, so the tie is decided on the binary value of the float. RFC 9651 section 4.1.5 rounds the decimal number half to even:

Marshal(NewItem(0.5015)) // "0.501", want "0.502" (0.5015 is stored as 0.50149999...)
Marshal(NewItem(2.0005)) // "2.001", want "2.0"   (2.0005 is stored as 2.00050000...)

The official suite added these cases in httpwg/structured-field-tests#114, which is why the dependabot bump in #27 fails CI (4 serialization tests).

The fix rounds the shortest decimal form of the float (strconv.FormatFloat(d, 'f', -1, 64)) as a string, half to even. Two small things in the same function:

  • NaN was written out as NaN; NaN and infinities now return ErrInvalidDecimal.
  • A negative value that rounds to zero (-0.0001) gave -0.0; it now gives 0.0, since the sign is only added when the rounded value is below zero.

This also bumps structured-field-tests to 10781e4, the same commit as #27, so the official tests cover it.

Testing:

  • New cases in TestMarshalDecimal; 6 of them fail on main and pass now.
  • go test ./..., go vet and golangci-lint are clean.
  • 1M random floats (many exact .xxx5 ties) against Python's Decimal(repr(x)).quantize(Decimal("0.001"), ROUND_HALF_EVEN): main differs on 14,408, this branch on 0.

marshalDecimal rounded d/0.001 in binary, so a tie like 0.5015 (stored
as 0.50149999...) went down and 2.0005 (stored as 2.00050000...) went
up. RFC 9651 section 4.1.5 rounds the decimal number, and the official
test suite now has cases for this.

Round the shortest decimal form of the float instead. Also fail on NaN
and infinities (NaN was written out as "NaN") and drop the sign when a
negative value rounds to zero.

Bump structured-field-tests to 10781e4 (same as dunglas#27), which has the new
tie-to-even cases.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant