C# Reference ยท Strings and Text
Culture-aware number formatting
Reference for number formatting in C#: format specifiers, NumberFormatInfo, separators, negative patterns and parsing numbers with a chosen culture.
Turning a number into text involves two decisions: the shape (digits after the point, grouping, percent, currency) and the symbols (which character is the decimal separator, which is the group separator, what the currency sign looks like). The shape comes from a format string such as "N2" or "P1". The symbols come from a NumberFormatInfo, usually obtained from a CultureInfo.
Every numeric type's ToString, TryParse, Parse and string interpolation accept an IFormatProvider. Pass CultureInfo.InvariantCulture for data that programs exchange, and a user's culture for display. You can also build or change a NumberFormatInfo yourself when you need a specific style, such as a space as the group separator.
using System.Globalization; var nfi = new NumberFormatInfo { NumberGroupSeparator = " ", NumberDecimalSeparator = "," }; string text = 1234567.891.ToString("N2", nfi); // 1 234 567,89
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public sealed class NumberFormatInfo : IFormatProvider { public static NumberFormatInfo InvariantInfo { get; } public static NumberFormatInfo CurrentInfo { get; } public string NumberDecimalSeparator { get; set; } public string NumberGroupSeparator { get; set; } public int NumberDecimalDigits { get; set; } public int[] NumberGroupSizes { get; set; } public int NumberNegativePattern { get; set; } public string CurrencySymbol { get; set; } public int CurrencyPositivePattern { get; set; } public string PercentSymbol { get; set; } public string NegativeSign { get; set; } public string NaNSymbol { get; set; } public string PositiveInfinitySymbol { get; set; } } // Used with: Number.ToString(string format, IFormatProvider provider) // Number.Parse(string s, NumberStyles style, IFormatProvider provider)
| Name | Description |
|---|---|
NumberDecimalSeparator / NumberGroupSeparator |
Characters used by N, F and general parsing. |
NumberGroupSizes |
Digits per group, from the right. { 3 } is the usual thousands grouping. |
NumberDecimalDigits |
Default digit count when the format has no number, as in "N". |
CurrencySymbol, CurrencyPositivePattern |
What C prints and where it goes. |
PercentSymbol |
Symbol for P. |
NumberStyles |
For parsing: which characters are allowed (whitespace, sign, thousands, decimal point, exponent, parentheses, currency). |
Returns: formatting returns a string. Parse returns the number; TryParse returns bool and the number through out.
Errors / undefined behavior: Parse throws FormatException for text the style does not allow and OverflowException when the value does not fit. Assigning an invalid pattern number (outside the documented range) throws ArgumentOutOfRangeException. The built-in InvariantInfo is read-only.
Usage notes
- Defaults parse generously, but not with groups.
int.Parseanddouble.Parsedefault toNumberStyles.IntegerandNumberStyles.Float | AllowThousandsrespectively, so check the overload:double.TryParse("1,234.5", NumberStyles.Float, ...)is false in the example above, whileNumberStyles.Numberaccepts it. - Round trips.
ToString("R")or justToString()ondoubleandfloatproduces the shortest text that parses back to the same value in modern .NET. Always use the same culture on both sides. - Group sizes. Some cultures group digits differently (the Indian 3,2,2 style).
NumberGroupSizescontrols it, so do not hard-code a thousands comma in your own code. - Never parse user input without a policy. Decide the culture, the
NumberStylesand useTryParse. AParsecall that works on your machine can throwFormatExceptionon a user's. - Rounding. Formatting only changes the text, never the stored value. On exact ties the result can surprise you: the last line of the second example prints
2 4 -2for2.5,3.5and-2.5with"F0". When the rounding rule matters (money, reports), round first withMath.Round()and an explicitMidpointRounding, then format. - Special values.
NaNand the infinities print usingNaNSymbol,PositiveInfinitySymbolandNegativeInfinitySymbol, which the invariant culture sets toNaN,Infinityand-Infinity. - Invariant globalization. This site's runner has only the invariant culture, so the examples build their own
NumberFormatInfoto show other symbols. On a normal machine you would useCultureInfo.GetCultureInfo("de-DE").NumberFormat. - Thread safety. A
NumberFormatInfoyou create is safe to share after you stop changing it; callNumberFormatInfo.ReadOnly(nfi)to make that explicit.