Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

NumberFormatInfo — numeric formatting rules

NumberFormatInfo supplies rules for formatting and parsing numbers, including separators and currency symbols. Learn its core methods, the distinction between current and invariant settings, and how to create a custom configuration safely.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

using System.Globalization;
NumberFormatInfo nfi = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
string text = value.ToString("N2", nfi);
NumberFormatInfo frozen = NumberFormatInfo.ReadOnly(nfi);

NumberFormatInfo in System.Globalization is an IFormatProvider for numeric formatting and parsing. Pass it to methods such as decimal.ToString and decimal.Parse; it does not itself expose Parse or a numeric ToString method. NumberDecimalSeparator and NumberGroupSeparator control number formatting; currencies and percentages have separate properties.

The core course methods (“NumberFormatInfo course methods”) are GetInstance, GetFormat, Clone, and ReadOnly. GetInstance(provider) retrieves the provider's settings, falling back to the current culture when it cannot obtain them. It does not guarantee an editable copy. GetFormat(typeof(NumberFormatInfo)) returns the current object; another type produces null.

Clone() returns a writable copy as object, so a cast is needed. ReadOnly(nfi) returns a read-only object—use the returned reference. IsReadOnly reports this state; assigning a property on such an object throws InvalidOperationException. ReadOnly(null) throws ArgumentNullException.

CurrentInfo depends on the current culture. If CultureInfo.CurrentCulture is set to a writable culture clone, CurrentInfo can return that clone's writable NumberFormatInfo. InvariantInfo supplies culture-independent rules and is read-only. The example clones InvariantInfo, sets separators, and uses "N2" for grouping with two decimal places. Parsing uses the same rules together with NumberStyles.Number. The code targets net10.0 and does not require preview language features.

Examples

using System;
using System.Globalization;

NumberFormatInfo nfi = (NumberFormatInfo)NumberFormatInfo.InvariantInfo.Clone();
nfi.NumberDecimalSeparator = ",";
nfi.NumberGroupSeparator = "_";
nfi.NumberGroupSizes = new[] { 3 };

NumberFormatInfo frozen = NumberFormatInfo.ReadOnly(nfi);
string text = 12345.67m.ToString("N2", frozen);
Console.WriteLine(text);

decimal parsed = decimal.Parse(text, NumberStyles.Number, frozen);
Console.WriteLine(parsed.ToString("F2", CultureInfo.InvariantCulture));
Console.WriteLine(frozen.IsReadOnly);

Result

12_345,67
12345.67
True

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources