Skip to content

Serialize decimals that round to a whole number with a fractional digit - #86

Merged
evert merged 2 commits into
evert:mainfrom
gyanu2507:fix/decimal-whole-number
Oct 10, 2026
Merged

evert merged 2 commits into
evert:mainfrom
gyanu2507:fix/decimal-whole-number

Conversation

@gyanu2507

Copy link
Copy Markdown
Contributor

Decimals that round to a whole number serialize to a string that ends in a period:

serializeItem(1.0001);  // '1.'
serializeItem(9.9999);  // '10.'
serializeItem(-0.0001); // '-0.'

That isn't a valid Decimal, and this library's own parser rejects it:

parseItem(serializeItem(1.0001));
// ParseError: Parse error: Decimal cannot end on a period at offset 2

RFC 9651 section 4.1.5 (same as RFC 8941) says "If input_decimal's fractional component is zero, append '0' to output", so the expected values are 1.0, 10.0 and -0.0.

serializeDecimal rounds with toFixed(3) and then strips trailing zeros with replace(/0+$/, ''). When all three fractional digits are zero, that also leaves nothing after the period. The fix appends a 0 in that case. Everything else in serializeDecimal is unchanged, including the 12-digit check, which already runs on the rounded value.

The httpwg tests don't catch this because their serialization inputs that round to a whole number are integers in JavaScript.

Testing

Added a case to the serializeItem tests in test/serializer-tests.js that serializes 1.0001, 9.9999 and -0.0001, checks the output, and parses it back.

  • make test (lint, build, httpwg tests and the serializer tests): 2823 pass, 0 fail.
  • Without the change in src/serializer.ts, the new test fails and everything else passes.

I also added a changelog entry under an unreleased 2.1.1 heading. Happy to change or drop that if you'd rather write it yourself.

serializeDecimal rounds with toFixed(3) and strips trailing zeros, so 1.0001
became "1." and 9.9999 became "10.". RFC 9651 section 4.1.5 requires a 0
after the period when the fractional component is zero, and parseItem rejects
both strings with "Decimal cannot end on a period".
@evert

evert commented Oct 10, 2026

Copy link
Copy Markdown
Owner

Dang, thank you!

@evert
evert merged commit 567e024 into evert:main Oct 10, 2026
5 checks passed
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.

2 participants