Skip to content

ToString/TryFormat throw FormatException for every format except "G": $"{x:F2}", "N2" and "0.00" all crash #134

Description

@matt-edmondson

What's wrong

PreciseNumber implements IFormattable/ISpanFormattable but rejects every format string other than empty or "G".

Where

PreciseNumber/PreciseNumber.cs:1354-1358 (TryFormat, which ToString(format, provider) goes through):

if (!format.IsEmpty && !format.Equals("G", StringComparison.OrdinalIgnoreCase))
{
    throw new FormatException();
}

Failure scenarios

Confirmed with a scratch app:

  • x.ToString("F2", CultureInfo.InvariantCulture) throws FormatException.
  • $"{x:0.00}" and string.Format("{0:N2}", x) throw.
  • Generic INumber<T> code that formats with a standard format string, logging templates such as {Value:N2}, and UI string-format bindings all fail at runtime, with a bare FormatException that has no message.
  • Output is always fixed-point with no E form, so a value like 1e-1000000 can only be rendered as a million-character string.

This is separate from #132, which is about NumberStyles in Parse.

Suggested fix

  • Support at least:
    • F<n> and N<n>: Round(n) plus culture decimal and group separators from the provider.
    • E<n>: scientific notation, built from the significand and exponent.
    • R: same as G.
  • For custom or unknown format strings, fall back to G (or throw a FormatException with a message naming the supported formats) rather than throwing a bare one.
  • Add tests for F2, N2, E5, R, and an interpolated {x:F2}.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    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