Skip to content
Tutorials Center
My learning

Topics

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.

C#
using System.Globalization;

var nfi = new NumberFormatInfo { NumberGroupSeparator = " ", NumberDecimalSeparator = "," };
string text = 1234567.891.ToString("N2", nfi);   // 1 234 567,89

Try it

C# Format shapes with a custom NumberFormatInfo

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.

C# Parsing depends on the same symbols

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

C#
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.Parse and double.Parse default to NumberStyles.Integer and NumberStyles.Float | AllowThousands respectively, so check the overload: double.TryParse("1,234.5", NumberStyles.Float, ...) is false in the example above, while NumberStyles.Number accepts it.
  • Round trips. ToString("R") or just ToString() on double and float produces 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). NumberGroupSizes controls it, so do not hard-code a thousands comma in your own code.
  • Never parse user input without a policy. Decide the culture, the NumberStyles and use TryParse. A Parse call that works on your machine can throw FormatException on 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 -2 for 2.5, 3.5 and -2.5 with "F0". When the rounding rule matters (money, reports), round first with Math.Round() and an explicit MidpointRounding, then format.
  • Special values. NaN and the infinities print using NaNSymbol, PositiveInfinitySymbol and NegativeInfinitySymbol, which the invariant culture sets to NaN, Infinity and -Infinity.
  • Invariant globalization. This site's runner has only the invariant culture, so the examples build their own NumberFormatInfo to show other symbols. On a normal machine you would use CultureInfo.GetCultureInfo("de-DE").NumberFormat.
  • Thread safety. A NumberFormatInfo you create is safe to share after you stop changing it; call NumberFormatInfo.ReadOnly(nfi) to make that explicit.