Skip to content

fix: support scientific notation in parse() for roundtrip consistency#285

Open
mahmoodhamdi wants to merge 1 commit intovercel:mainfrom
mahmoodhamdi:fix/parse-scientific-notation
Open

fix: support scientific notation in parse() for roundtrip consistency#285
mahmoodhamdi wants to merge 1 commit intovercel:mainfrom
mahmoodhamdi:fix/parse-scientific-notation

Conversation

@mahmoodhamdi
Copy link
Copy Markdown

Summary

format() can produce scientific notation for very large millisecond values (e.g., JavaScript coerces large numbers to strings like "5.7e+297y"), but parse() returns NaN for these strings because its regex doesn't match the e notation. This breaks the roundtrip contract between the two functions.

I ran into this while using ms for cache TTL calculations where intermediate values can get large before being clamped — parse(format(bigValue)) silently returning NaN was unexpected.

Changes

  • Updated the regex number pattern in parse() from -?\d*\.?\d+ to -?\d*\.?\d+(?:e[+-]?\d+)? to accept scientific notation
  • Added tests for scientific notation parsing (1e3ms, 1.5e2ms, 1e+3ms, 1e-3ms)
  • Added roundtrip tests verifying parse(format(N)) does not return NaN for large values
  • Added roundtrip tests for common units through ms()

Checks

  • pnpm test — 173 tests pass (Node.js + Edge Runtime)
  • pnpm typecheck — clean
  • pnpm lint — clean
  • 100% code coverage maintained

Fixes #284

format() produces scientific notation for very large millisecond values
(e.g., `ms(Number.MAX_SAFE_INTEGER)` → `"285616y"`), and for even larger
values JavaScript's number-to-string coercion uses exponential notation
(e.g., `"5.7e+297y"`). The parse() regex did not accept the `e` notation,
causing it to return NaN for format()'s own output.

Update the regex number pattern from `-?\d*\.?\d+` to
`-?\d*\.?\d+(?:e[+-]?\d+)?` so that parseFloat-compatible scientific
notation is matched correctly.

Fixes vercel#284
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.

format() produces output that parse() cannot parse back (roundtrip failure with large numbers)

1 participant