Formatting numeric results table

Domains: C#

The following table shows supported format specifiers for formatting numeric results. The formatted result in the last column corresponds to the "en-US" CultureInfo.

Format specifier        Description           Examples   Result
C or c         Currency string s = $"{2.5:C}";

string s = $"{-2.5:C}";
       $2.50

      ($2.50)
D or d         Decimal string s = $"{25:D5}";       00025
E or e         Exponential string s = $"{250000:E2}";      2.50E+005
F or f         Fixed-point string s = $"{2.5:F2}";

string s = $"{2.5:F0}";
       2.50

          3
G or g         General string s = $"{2.5:G}";         2.5
N or n         Numeric string s = $"{2500000:N}";     2,500,000.00
P or p         Percent string s = $"{0.25:P}";         25.00%
R or r         Round-trip string s = $"{2.5:R}";           2.5
X or x         Hexadecimal string s = $"{250:X}";

string s = $"{0xffff:X}";
          FA

         FFFF

Remarks

You use a format specifier to create a format string. The format string is of the following form: Axx, where

  • A is the format specifier, which controls the type of formatting applied to the numeric value.
  • xx is the precision specifier, which affects the number of digits in the formatted output. The value of the precision specifier ranges from 0 to 99.

The decimal ("D" or "d") and hexadecimal ("X" or "x") format specifiers are supported only for integral types. The round-trip ("R" or "r") format specifier is supported only for Single, Double, and BigIntegertypes.

Standard numeric format strings are supported by:

  • Some overloads of the ToString method of all numeric types. For example, you can supply a numeric format string to the Int32.ToString(String) and Int32.ToString(String, IFormatProvider)methods.
  • The .NET composite formatting feature, which is supported by the String.Format method, for example.
  • Interpolated strings.
Page structure