Skip to content

JsonTextReader loses precision for double/decimal number tokens — no way to access raw source text - #3108

Open
sachinkale246 wants to merge 1 commit into
JamesNK:masterfrom
sachinkale246:master
Open

JsonTextReader loses precision for double/decimal number tokens — no way to access raw source text#3108
sachinkale246 wants to merge 1 commit into
JamesNK:masterfrom
sachinkale246:master

Conversation

@sachinkale246

Copy link
Copy Markdown

When parsing JSON into a JToken, there is no way to preserve exact numeric precision for floating-point values that are representable by double or decimal but not both:

  • double.MaxValue (~1.8e308) overflows decimal → FloatParseHandling.Decimal throws
  • decimal.MinValue / high-precision decimals lose significant digits → FloatParseHandling.Double rounds
  • There is no fallback mode that picks the best type per token
  • JsonConverter.ReadJson cannot recover the raw source text because _stringReference is cleared before the token is emitted
    JSON and code related to the issue

[1.7976931348623157E+308, 1.23456789012345678901234567890]

// double.MaxValue overflows decimal → throws with FloatParseHandling.Decimal
// high-precision decimal loses digits with FloatParseHandling.Double (default)
var reader = new JsonTextReader(new StringReader(json));
reader.FloatParseHandling = FloatParseHandling.Double; // or Decimal — neither handles both
var token = JToken.ReadFrom(reader);

Suggested fix (with PR)
Two additions to JsonTextReader:

  1. PreserveNumberText / NumberText — opt-in flag that captures the raw source text of each number token as a string? property, accessible after Read() returns. Zero cost when disabled.
  2. protected virtual OnNumberParsed(string rawText, ref JsonToken tokenType, ref object value) — virtual hook called just before SetToken, allowing subclasses to replace the default parsed value with a more precise type (e.g. try decimal first, fall back to double) without reflection hacks.

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