Maximum precision for numeric format strings

The maximum precision when formatting numbers as strings using ToString and TryFormat has been changed from Int32.MaxValue to 999,999,999. (The maximum precision was previously changed to Int32.MaxValue in .NET 6.)

In addition, the maximum exponent allowed when parsing a BigInteger from a string has been limited to 999,999,999.

Previous behavior

In .NET 6, the standard numeric format parsing logic was limited to a precision of Int32.MaxValue or less. The intended behavior was to throw a FormatException for any precision larger than Int32.MaxValue. However, due to a bug, .NET 6 didn't throw that exception for some such inputs. The intended behavior was:

double d = 123.0;

d.ToString("E" + int.MaxValue.ToString()); // Doesn't throw.

long intMaxPlus1 = (long)int.MaxValue + 1;
string intMaxPlus1String = intMaxPlus1.ToString();
Assert.Throws<FormatException>(() => d.ToString("E" + intMaxPlus1String)); // Throws.

In addition, there was no limit on the exponent size when parsing a BigInteger from a string.

New behavior

Starting in .NET 7, .NET supports precision up to 999,999,999. A FormatException is thrown if the precision is greater than 999,999,999. This change was implemented in the parsing logic that affects all numeric types.

double d = 123.0;
Assert.Throws<FormatException>(() => d.ToString("E" + int.MaxValue.ToString())); // Throws.

long intMaxPlus1 = (long)int.MaxValue + 1;
string intMaxPlus1String = intMaxPlus1.ToString();
Assert.Throws<FormatException>(() => d.ToString("E" + intMaxPlus1String)); // Throws.

d.ToString("E999999999"); // Doesn't throw.

d.ToString("E00000999999999"); // Doesn't throw.

In addition, if you attempt to parse a BigInteger with an exponent greater than 999,999,999 from a string, a FormatException is thrown.

Version introduced

.NET 7

Type of breaking change

This change can affect binary compatibility.

Reason for change

The behavior that was introduced in .NET 6 was intended to throw a FormatException for any precision larger than Int32.MaxValue. However, due to a bug, it did not throw that exception for some inputs larger than the maximum. This change fixes the bug by limiting the precision to 999,999,999.

In most cases, no action is necessary, because it's unlikely that you're already using a precision higher than 999,999,999 in your format strings.

Affected APIs

This change was implemented in the parsing logic that affects all numeric types.

See also