Skip to content

Parse throws OverflowException for "0e99999999999" and for representable values near exponent int.MinValue, so ToString("E") output there can't be parsed back #178

Closed

Description

@matt-edmondson

What's wrong

In Parse (PreciseNumber/PreciseNumber.cs:1291), exponent = checked(exponent - decimalDigits) subtracts every written fraction digit — including padding zeros — in checked int arithmetic before the value is normalized. The exponent text also goes through int parsing even when the significand is zero.

Reproduced at 907bd2d (invariant culture, NumberStyles.Float):

var x = PreciseNumber.Parse("1e-2147483646", inv);   // fine
var s = x.ToString("E", inv);                         // "1.000000E-2147483646"
PreciseNumber.TryParse(s, NumberStyles.Float, inv, out _); // false — can't read its own output

PreciseNumber.Parse("2.500E-2147483647", inv);  // OverflowException; the value 25e-2147483648 is representable
PreciseNumber.Parse("1.0e-2147483648", inv);    // OverflowException; "1e-2147483648" parses fine
PreciseNumber.Parse("0e99999999999", NumberStyles.Float, inv); // OverflowException; decimal and double return 0

Why it matters

At these magnitudes the plain format would be a ~2 GB string, so "E" is the only text form that can round-trip a value — and it doesn't. Serialized values (e.g. through a round-trip string JSON converter) at the extreme end of the range fail to load. A zero with a large written exponent is valid input that every BCL numeric type accepts.

Suggested fix

  • Strip trailing zeros from the collected digits (adjusting decimalDigits) before computing the exponent, or do the exponent arithmetic in long and range-check only after normalizing.
  • Return Zero when the significand is zero, regardless of the exponent text (parse the exponent as long/saturating so huge exponents don't throw first).

Acceptance: each input above parses to the expected value, and Parse(x.ToString("E")) round-trips for values with exponents within 10 of int.MinValue/int.MaxValue.

Activity

  1. matt-edmondson commented on Oct 29, 2026

    @matt-edmondson
    ContributorAuthor

    Triage


    Generated by Claude Code

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

Metadata

Metadata

Labels

bugSomething isn't working

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions