.NET Framework 4 Standard Numeric Format Strings Updated: March 2011 Standard numeric format strings are used to format common numeric types. A standard numeric format string takes the form Axx, where A is an alphabetic character called the format specifier, and xx is an optional integer called the precision specifier. The precision specifier ranges from 0 to 99 and affects the number of digits in the result. Any numeric format string that contains more than one alphabetic character, including white space, is interpreted as a custom numeric format string. For more information, see Custom Numeric Format Strings. 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 ToString(String) and ToString(String, IFormatProvider) methods of the Int32 type. Standard numeric format strings are also supported by the .NET Framework composite formatting feature, which is used by some Write and WriteLine methods of the Console and StreamWriter classes, the String..::.Format method, and the StringBuilder..::.AppendFormat method. Tip |
|---|
You can download the Format Utility, an application that enables you to apply format strings to either numeric or date and time values and displays the result string. |
The following table describes the standard numeric format specifiers and displays sample output produced by each format specifier. See the Notes section for additional information about using standard numeric format strings, and the Example section for a comprehensive illustration of their use. Format specifier | Name | Description | Examples |
|---|
"C" or "c" | Currency | Result: A currency value. Supported by: All numeric types. Precision specifier: Number of decimal digits. Default precision specifier: Defined by System.Globalization..::.NumberFormatInfo. More information: The Currency ("C") Format Specifier. | 123.456 ("C", en-US) -> $123.46 123.456 ("C", fr-FR) -> 123,46 € 123.456 ("C", ja-JP) -> ¥123 -123.456 ("C3", en-US) -> ($123.456) -123.456 ("C3", fr-FR) -> -123,456 € -123.456 ("C3", ja-JP) -> -¥123.456 | "D" or "d" | Decimal | Result: Integer digits with optional negative sign. Supported by: Integral types only. Precision specifier: Minimum number of digits. Default precision specifier: Minimum number of digits required. More information: The Decimal("D") Format Specifier. | 1234 ("D") -> 1234 -1234 ("D6") -> -001234 | "E" or "e" | Exponential (scientific) | Result: Exponential notation. Supported by: All numeric types. Precision specifier: Number of decimal digits. Default precision specifier: 6. More information: The Exponential ("E") Format Specifier. | 1052.0329112756 ("E", en-US) -> 1.052033E+003 1052.0329112756 ("e", fr-FR) -> 1,052033e+003 -1052.0329112756 ("e2", en-US) -> -1.05e+003 -1052.0329112756 ("E2", fr_FR) -> -1,05E+003 | "F" or "f" | Fixed-point | Result: Integral and decimal digits with optional negative sign. Supported by: All numeric types. Precision specifier: Number of decimal digits. Default precision specifier: Defined by System.Globalization..::.NumberFormatInfo. More information: The Fixed-Point ("F") Format Specifier. | 1234.567 ("F", en-US) -> 1234.57 1234.567 ("F", de-DE) -> 1234,57 1234 ("F1", en-US) -> 1234.0 1234 ("F1", de-DE) -> 1234,0 -1234.56 ("F4", en-US) -> -1234.5600 -1234.56 ("F4", de-DE) -> -1234,5600 | "G" or "g" | General | Result: The most compact of either fixed-point or scientific notation. Supported by: All numeric types. Precision specifier: Number of significant digits. Default precision specifier: Depends on numeric type. More information: The General ("G") Format Specifier. | -123.456 ("G", en-US) -> -123.456 123.456 ("G", sv-SE) -> -123,456 123.4546 ("G4", en-US) -> 123.5 123.4546 ("G4", sv-SE) -> 123,5 -1.234567890e-25 ("G", en-US) -> -1.23456789E-25 -1.234567890e-25 ("G", sv-SE) -> -1,23456789E-25 | "N" or "n" | Number | Result: Integral and decimal digits, group separators, and a decimal separator with optional negative sign. Supported by: All numeric types. Precision specifier: Desired number of decimal places. Default precision specifier: Defined by System.Globalization..::.NumberFormatInfo. More information: The Numeric ("N") Format Specifier. | 1234.567 ("N", en-US) -> 1,234.57 1234.567 ("N", ru-RU) -> 1 234,57 1234 ("N", en-US) -> 1,234.0 1234 ("N", ru-RU) -> 1 234,0 -1234.56 ("N", en-US) -> -1,234.560 -1234.56 ("N", ru-RU) -> -1 234,560 | "P" or "p" | Percent | Result: Number multiplied by 100 and displayed with a percent symbol. Supported by: All numeric types. Precision specifier: Desired number of decimal places. Default precision specifier: Defined by System.Globalization..::.NumberFormatInfo. More information: The Percent ("P") Format Specifier. | 1 ("P", en-US) -> 100.00 % 1 ("P", fr-FR) -> 100,00 % -0.39678 ("P1", en-US) -> -39.7 % -0.39678 ("P1", fr-FR) -> -39,7 % | "R" or "r" | Round-trip | Result: A string that can round-trip to an identical number. Supported by: Single, Double, and BigInteger. Precision specifier: Ignored. More information: The Round-trip ("R") Format Specifier. | 123456789.12345678 ("R") -> 123456789.12345678 -1234567890.12345678 ("R") -> -1234567890.1234567 | "X" or "x" | Hexadecimal | Result: A hexadecimal string. Supported by: Integral types only. Precision specifier: Number of digits in the result string. More information: The HexaDecimal ("X") Format Specifier. | 255 ("X") -> FF -1 ("x") -> ff 255 ("x4") -> 00ff -1 ("X4") -> 00FF | Any other single character | Unknown specifier | Result: Throws a FormatException at run time. | |

Using Standard Numeric Format Strings
A standard numeric format string can be used to define the formatting of a numeric value in one of two ways: It can be passed to an overload of the ToString method that has a format parameter. The following example formats a numeric value as a currency string in the current (in this case, the en-US) culture.
Dim value As Decimal = 123.456d
Console.WriteLine(value.ToString("C2"))
' Displays $123.46
decimal value = 123.456m;
Console.WriteLine(value.ToString("C2"));
// Displays $123.46
It can be supplied as the formatString parameter in a format item used with such methods as String..::.Format, Console..::.WriteLine, and StringBuilder..::.AppendFormat. For more information, see Composite Formatting. The following example uses a format item to insert a currency value in a string.
Dim value As Decimal = 123.456d
Console.WriteLine("Your account balance is {0:C2}.", value)
' Displays "Your account balance is $123.46."
decimal value = 123.456m;
Console.WriteLine("Your account balance is {0:C2}.", value);
// Displays "Your account balance is $123.46."
The following sections provide detailed information about each of the standard numeric format strings.

The Currency ("C") Format Specifier
The "C" (or currency) format specifier converts a number to a string that represents a currency amount. The precision specifier indicates the desired number of decimal places in the result string. If the precision specifier is omitted, the default precision is defined by the NumberFormatInfo..::.CurrencyDecimalDigits property. If the value to be formatted has more than the specified or default number of decimal places, the fractional value is rounded in the result string. If the value to the right of the number of specified decimal places is 5 or greater, the last digit in the result string is rounded away from zero. The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the NumberFormatInfo properties that control the formatting of the returned string. The following example formats a Double value with the currency format specifier.
Dim value As Double = 12345.6789
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture))
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture))
Console.WriteLine(value.ToString("C3", _
CultureInfo.CreateSpecificCulture("da-DK")))
' The example displays the following output on a system whose
' current culture is English (United States):
' $12,345.68
' $12,345.679
' kr 12.345,679
double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3",
CultureInfo.CreateSpecificCulture("da-DK")));
// The example displays the following output on a system whose
// current culture is English (United States):
// $12,345.68
// $12,345.679
// kr 12.345,679
Back to table

The Decimal ("D") Format Specifier
The "D" (or decimal) format specifier converts a number to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. This format is supported only for integral types. The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. If no precision specifier is specified, the default is the minimum value required to represent the integer without leading zeros. The result string is affected by the formatting information of the current NumberFormatInfo object. As the following table shows, a single property affects the formatting of the result string. NumberFormatInfo property | Description |
|---|
NegativeSign | Defines the string that indicates that a number is negative. |
The following example formats an Int32 value with the decimal format specifier.
Dim value As Integer
value = 12345
Console.WriteLine(value.ToString("D"))
' Displays 12345
Console.WriteLine(value.ToString("D8"))
' Displays 00012345
value = -12345
Console.WriteLine(value.ToString("D"))
' Displays -12345
Console.WriteLine(value.ToString("D8"))
' Displays -00012345
int value;
value = 12345;
Console.WriteLine(value.ToString("D"));
// Displays 12345
Console.WriteLine(value.ToString("D8"));
// Displays 00012345
value = -12345;
Console.WriteLine(value.ToString("D"));
// Displays -12345
Console.WriteLine(value.ToString("D8"));
// Displays -00012345
Back to table

The Exponential ("E") Format Specifier
The exponential ("E") format specifier converts a number to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", where each "d" indicates a digit (0-9). The string starts with a minus sign if the number is negative. Exactly one digit always precedes the decimal point. The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier is omitted, a default of six digits after the decimal point is used. The case of the format specifier indicates whether to prefix the exponent with an "E" or an "e". The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum, if required. The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the NumberFormatInfo properties that control the formatting of the returned string. NumberFormatInfo property | Description |
|---|
NegativeSign | Defines the string that indicates that a number is negative for both the coefficient and exponent. | NumberDecimalSeparator | Defines the string that separates the integral digit from decimal digits in the coefficient. | PositiveSign | Defines the string that indicates that an exponent is positive. |
The following example formats a Double value with the exponential format specifier.
Dim value As Double = 12345.6789
Console.WriteLine(value.ToString("E", CultureInfo.InvariantCulture))
' Displays 1.234568E+004
Console.WriteLine(value.ToString("E10", CultureInfo.InvariantCulture))
' Displays 1.2345678900E+004
Console.WriteLine(value.ToString("e4", CultureInfo.InvariantCulture))
' Displays 1.2346e+004
Console.WriteLine(value.ToString("E", _
CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 1,234568E+004
double value = 12345.6789;
Console.WriteLine(value.ToString("E", CultureInfo.InvariantCulture));
// Displays 1.234568E+004
Console.WriteLine(value.ToString("E10", CultureInfo.InvariantCulture));
// Displays 1.2345678900E+004
Console.WriteLine(value.ToString("e4", CultureInfo.InvariantCulture));
// Displays 1.2346e+004
Console.WriteLine(value.ToString("E",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 1,234568E+004
Back to table

The Fixed-Point ("F") Format Specifier
The fixed-point ("F) format specifier converts a number to a string of the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The string starts with a minus sign if the number is negative. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the current NumberFormatInfo..::.NumberDecimalDigits property supplies the numeric precision. The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the properties of the NumberFormatInfo object that control the formatting of the result string. NumberFormatInfo property | Description |
|---|
NegativeSign | Defines the string that indicates that a number is negative. | NumberDecimalSeparator | Defines the string that separates integral digits from decimal digits. | NumberDecimalDigits | Defines the default number of decimal digits. This value can be overridden by using the precision specifier. |
The following example formats a Double and an Int32 value with the fixed-point format specifier.
Dim integerNumber As Integer
integerNumber = 17843
Console.WriteLine(integerNumber.ToString("F", CultureInfo.InvariantCulture))
' Displays 17843.00
integerNumber = -29541
Console.WriteLine(integerNumber.ToString("F3", CultureInfo.InvariantCulture))
' Displays -29541.000
Dim doubleNumber As Double
doubleNumber = 18934.1879
Console.WriteLine(doubleNumber.ToString("F", CultureInfo.InvariantCulture))
' Displays 18934.19
Console.WriteLine(doubleNumber.ToString("F0", CultureInfo.InvariantCulture))
' Displays 18934
doubleNumber = -1898300.1987
Console.WriteLine(doubleNumber.ToString("F1", CultureInfo.InvariantCulture))
' Displays -1898300.2
Console.WriteLine(doubleNumber.ToString("F3", _
CultureInfo.CreateSpecificCulture("es-ES")))
' Displays -1898300,199
int integerNumber;
integerNumber = 17843;
Console.WriteLine(integerNumber.ToString("F",
CultureInfo.InvariantCulture));
// Displays 17843.00
integerNumber = -29541;
Console.WriteLine(integerNumber.ToString("F3",
CultureInfo.InvariantCulture));
// Displays -29541.000
double doubleNumber;
doubleNumber = 18934.1879;
Console.WriteLine(doubleNumber.ToString("F", CultureInfo.InvariantCulture));
// Displays 18934.19
Console.WriteLine(doubleNumber.ToString("F0", CultureInfo.InvariantCulture));
// Displays 18934
doubleNumber = -1898300.1987;
Console.WriteLine(doubleNumber.ToString("F1", CultureInfo.InvariantCulture));
// Displays -1898300.2
Console.WriteLine(doubleNumber.ToString("F3",
CultureInfo.CreateSpecificCulture("es-ES")));
// Displays -1898300,199
Back to table

The General ("G") Format Specifier
The general ("G") format specifier converts a number to the most compact of either fixed-point or scientific notation, depending on the type of the number and whether a precision specifier is present. The precision specifier defines the maximum number of significant digits that can appear in the result string. If the precision specifier is omitted or zero, the type of the number determines the default precision, as indicated in the following table. Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and less than the precision specifier; otherwise, scientific notation is used. The result contains a decimal point if required, and trailing zeros after the decimal point are omitted. If the precision specifier is present and the number of significant digits in the result exceeds the specified precision, the excess trailing digits are removed by rounding. However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved. If scientific notation is used, the exponent in the result is prefixed with "E" if the format specifier is "G", or "e" if the format specifier is "g". The exponent contains a minimum of two digits. This differs from the format for scientific notation that is produced by the exponential format specifier, which includes a minimum of three digits in the exponent. The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the NumberFormatInfo properties that control the formatting of the result string. NumberFormatInfo property | Description |
|---|
NegativeSign | Defines the string that indicates that a number is negative. | NumberDecimalSeparator | Defines the string that separates integral digits from decimal digits. | NumberDecimalDigits | Defines the default number of decimal digits. This value can be overridden by using the precision specifier. | PositiveSign | Defines the string that indicates that an exponent is positive. |
The following example formats assorted floating-point values with the general format specifier.
Dim number As Double
number = 12345.6789
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture))
' Displays 12345.6789
Console.WriteLine(number.ToString("G", _
CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 12345,6789
Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture))
' Displays 12345.68
number = .0000023
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture))
' Displays 2.3E-06
Console.WriteLine(number.ToString("G", _
CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 2,3E-06
number = .0023
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture))
' Displays 0.0023
number = 1234
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture))
' Displays 1.2E+03
number = Math.Pi
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture))
' Displays 3.1416
double number;
number = 12345.6789;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 12345.6789
Console.WriteLine(number.ToString("G",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 12345,6789
Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture));
// Displays 12345.68
number = .0000023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 2.3E-06
Console.WriteLine(number.ToString("G",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 2,3E-06
number = .0023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 0.0023
number = 1234;
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));
// Displays 1.2E+03
number = Math.PI;
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));
// Displays 3.1416
Back to table

The Numeric ("N") Format Specifier
The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" indicates a negative number symbol if required, "d" indicates a digit (0-9), "," indicates a group separator, and "." indicates a decimal point symbol. The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier is omitted, the number of decimal places is defined by the current NumberFormatInfo..::.NumberDecimalDigits property. The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the NumberFormatInfo properties that control the formatting of the result string. NumberFormatInfo property | Description |
|---|
NegativeSign | Defines the string that indicates that a number is negative. | NumberNegativePattern | Defines the format of negative values, and specifies whether the negative sign is represented by parentheses or the NegativeSign property. | NumberGroupSizes | Defines the number of integral digits that appear between group separators. | NumberGroupSeparator | Defines the string that separates groups of integral numbers. | NumberDecimalSeparator | Defines the string that separates integral and decimal digits. | NumberDecimalDigits | Defines the default number of decimal digits. This value can be overridden by using a precision specifier. |
The following example formats assorted floating-point values with the number format specifier.
Dim dblValue As Double = -12445.6789
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture))
' Displays -12,445.68
Console.WriteLine(dblValue.ToString("N1", _
CultureInfo.CreateSpecificCulture("sv-SE")))
' Displays -12 445,7
Dim intValue As Integer = 123456789
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture))
' Displays 123,456,789.0
double dblValue = -12445.6789;
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture));
// Displays -12,445.68
Console.WriteLine(dblValue.ToString("N1",
CultureInfo.CreateSpecificCulture("sv-SE")));
// Displays -12 445,7
int intValue = 123456789;
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture));
// Displays 123,456,789.0
Back to table

The Percent ("P") Format Specifier
The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision supplied by the current PercentDecimalDigits property is used. The following table lists the NumberFormatInfo properties that control the formatting of the returned string. The following example formats floating-point values with the percent format specifier.
Dim number As Double = .2468013
Console.WriteLine(number.ToString("P", CultureInfo.InvariantCulture))
' Displays 24.68 %
Console.WriteLine(number.ToString("P", _
CultureInfo.CreateSpecificCulture("hr-HR")))
' Displays 24,68%
Console.WriteLine(number.ToString("P1", CultureInfo.InvariantCulture))
' Displays 24.7 %
double number = .2468013;
Console.WriteLine(number.ToString("P", CultureInfo.InvariantCulture));
// Displays 24.68 %
Console.WriteLine(number.ToString("P",
CultureInfo.CreateSpecificCulture("hr-HR")));
// Displays 24,68%
Console.WriteLine(number.ToString("P1", CultureInfo.InvariantCulture));
// Displays 24.7 %
Back to table

The Round-trip ("R") Format Specifier
The round-trip ("R") format specifier guarantees that a numeric value that is converted to a string will be parsed back into the same numeric value. This format is supported only for the Single, Double, and BigInteger types. When a BigInteger value is formatted using this specifier, its string representation contains all the significant digits in the BigInteger value. When a Single or Double value is formatted using this specifier, it is first tested using the general format, with 15 digits of precision for a Double and 7 digits of precision for a Single. If the value is successfully parsed back to the same numeric value, it is formatted using the general format specifier. If the value is not successfully parsed back to the same numeric value, it is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single. Although you can include a precision specifier, it is ignored. Round trips are given precedence over precision when using this specifier. The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the NumberFormatInfo properties that control the formatting of the result string. NumberFormatInfo property | Description |
|---|
NegativeSign | Defines the string that indicates that a number is negative. | NumberDecimalSeparator | Defines the string that separates integral digits from decimal digits. | PositiveSign | Defines the string that indicates that an exponent is positive. |
The following example formats Double values with the round-trip format specifier.
Dim value As Double
value = Math.Pi
Console.WriteLine(value.ToString("r"))
' Displays 3.1415926535897931
Console.WriteLine(value.ToString("r", _
CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 3,1415926535897931
value = 1.623e-21
Console.WriteLine(value.ToString("r"))
' Displays 1.623E-21
double value;
value = Math.PI;
Console.WriteLine(value.ToString("r"));
// Displays 3.1415926535897931
Console.WriteLine(value.ToString("r",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 3,1415926535897931
value = 1.623e-21;
Console.WriteLine(value.ToString("r"));
// Displays 1.623E-21
Back to table

The Hexadecimal ("X") Format Specifier
The hexadecimal ("X") format specifier converts a number to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for hexadecimal digits that are greater than 9. For example, use "X" to produce "ABCDEF", and "x" to produce "abcdef". This format is supported only for integral types. The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. The result string is not affected by the formatting information of the current NumberFormatInfo object. The following example formats Int32 values with the hexadecimal format specifier.
Dim value As Integer
value = &h2045e
Console.WriteLine(value.ToString("x"))
' Displays 2045e
Console.WriteLine(value.ToString("X"))
' Displays 2045E
Console.WriteLine(value.ToString("X8"))
' Displays 0002045E
value = 123456789
Console.WriteLine(value.ToString("X"))
' Displays 75BCD15
Console.WriteLine(value.ToString("X2"))
' Displays 75BCD15
int value;
value = 0x2045e;
Console.WriteLine(value.ToString("x"));
// Displays 2045e
Console.WriteLine(value.ToString("X"));
// Displays 2045E
Console.WriteLine(value.ToString("X8"));
// Displays 0002045E
value = 123456789;
Console.WriteLine(value.ToString("X"));
// Displays 75BCD15
Console.WriteLine(value.ToString("X2"));
// Displays 75BCD15
Back to table

Notes
Control Panel SettingsThe settings in the Regional and Language Options item in Control Panel influence the result string produced by a formatting operation. Those settings are used to initialize the NumberFormatInfo object associated with the current thread culture, which provides values used to govern formatting. Computers that use different settings generate different result strings. In addition, if the CultureInfo..::.CultureInfo(String) constructor is used to instantiate a new CultureInfo object that represents the same culture as the current system culture, any customizations established by the Regional and Language Options item in Control Panel will be applied to the new CultureInfo object. You can use the CultureInfo..::.CultureInfo(String, Boolean) constructor to create a CultureInfo object that does not reflect a system's customizations. NumberFormatInfo PropertiesFormatting is influenced by the properties of the current NumberFormatInfo object, which is provided implicitly by the current thread culture or explicitly by the IFormatProvider parameter of the method that invokes formatting. Specify a NumberFormatInfo or CultureInfo object for that parameter. Integral and Floating-Point Numeric TypesSome descriptions of standard numeric format specifiers refer to integral or floating-point numeric types. The integral numeric types are Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, and BigInteger. The floating-point numeric types are Decimal, Single, and Double. Floating-Point Infinities and NaN

Example
The following example formats an integral and a floating-point numeric value using the en-US culture and all the standard numeric format specifiers. This example uses two particular numeric types (Double and Int32), but would yield similar results for any of the other numeric base types (Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, BigInteger, Decimal, and Single).
Option Strict On
Imports System.Globalization
Imports System.Threading
Module NumericFormats
Public Sub Main()
' Display string representations of numbers for en-us culture
Dim ci As New CultureInfo("en-us")
' Output floating point values
Dim floating As Double = 10761.937554
Console.WriteLine("C: {0}", _
floating.ToString("C", ci)) ' Displays "C: $10,761.94"
Console.WriteLine("E: {0}", _
floating.ToString("E03", ci)) ' Displays "E: 1.076E+004"
Console.WriteLine("F: {0}", _
floating.ToString("F04", ci)) ' Displays "F: 10761.9376"
Console.WriteLine("G: {0}", _
floating.ToString("G", ci)) ' Displays "G: 10761.937554"
Console.WriteLine("N: {0}", _
floating.ToString("N03", ci)) ' Displays "N: 10,761.938"
Console.WriteLine("P: {0}", _
(floating/10000).ToString("P02", ci)) ' Displays "P: 107.62 %"
Console.WriteLine("R: {0}", _
floating.ToString("R", ci)) ' Displays "R: 10761.937554"
Console.WriteLine()
' Output integral values
Dim integral As Integer = 8395
Console.WriteLine("C: {0}", _
integral.ToString("C", ci)) ' Displays "C: $8,395.00"
Console.WriteLine("D: {0}", _
integral.ToString("D6")) ' Displays "D: 008395"
Console.WriteLine("E: {0}", _
integral.ToString("E03", ci)) ' Displays "E: 8.395E+003"
Console.WriteLine("F: {0}", _
integral.ToString("F01", ci)) ' Displays "F: 8395.0"
Console.WriteLine("G: {0}", _
integral.ToString("G", ci)) ' Displays "G: 8395"
Console.WriteLine("N: {0}", _
integral.ToString("N01", ci)) ' Displays "N: 8,395.0"
Console.WriteLine("P: {0}", _
(integral/10000).ToString("P02", ci)) ' Displays "P: 83.95 %"
Console.WriteLine("X: 0x{0}", _
integral.ToString("X", ci)) ' Displays "X: 0x20CB"
Console.WriteLine()
End Sub
End Module
using System;
using System.Globalization;
using System.Threading;
public class NumericFormats
{
public static void Main()
{
// Display string representations of numbers for en-us culture
CultureInfo ci = new CultureInfo("en-us");
// Output floating point values
double floating = 10761.937554;
Console.WriteLine("C: {0}",
floating.ToString("C", ci)); // Displays "C: $10,761.94"
Console.WriteLine("E: {0}",
floating.ToString("E03", ci)); // Displays "E: 1.076E+004"
Console.WriteLine("F: {0}",
floating.ToString("F04", ci)); // Displays "F: 10761.9376"
Console.WriteLine("G: {0}",
floating.ToString("G", ci)); // Displays "G: 10761.937554"
Console.WriteLine("N: {0}",
floating.ToString("N03", ci)); // Displays "N: 10,761.938"
Console.WriteLine("P: {0}",
(floating/10000).ToString("P02", ci)); // Displays "P: 107.62 %"
Console.WriteLine("R: {0}",
floating.ToString("R", ci)); // Displays "R: 10761.937554"
Console.WriteLine();
// Output integral values
int integral = 8395;
Console.WriteLine("C: {0}",
integral.ToString("C", ci)); // Displays "C: $8,395.00"
Console.WriteLine("D: {0}",
integral.ToString("D6", ci)); // Displays "D: 008395"
Console.WriteLine("E: {0}",
integral.ToString("E03", ci)); // Displays "E: 8.395E+003"
Console.WriteLine("F: {0}",
integral.ToString("F01", ci)); // Displays "F: 8395.0"
Console.WriteLine("G: {0}",
integral.ToString("G", ci)); // Displays "G: 8395"
Console.WriteLine("N: {0}",
integral.ToString("N01", ci)); // Displays "N: 8,395.0"
Console.WriteLine("P: {0}",
(integral/10000.0).ToString("P02", ci)); // Displays "P: 83.95 %"
Console.WriteLine("X: 0x{0}",
integral.ToString("X", ci)); // Displays "X: 0x20CB"
Console.WriteLine();
}
}

See Also

Change History
Date | History | Reason |
|---|
March 2011
| Added a link to the Format Utility. |
Information enhancement.
|
July 2010
| Noted that rounding away from zero is used with the "C" standard format string. |
Customer feedback.
|
|
.NET Framework 4 Cadenas con formato numérico estándar Las cadenas de formato numérico estándar se utilizan para dar formato a tipos numéricos comunes. Una cadena de formato numérico estándar presenta la forma Axx, donde A es un carácter alfabético que recibe el nombre de especificador de formato y xx es un entero opcional que recibe el nombre de especificador de precisión. El especificador de precisión está comprendido entre el 0 y el 99 y afecta al número de dígitos del resultado. Cualquier cadena de formato numérico que contenga más de un carácter alfabético, incluido el espacio en blanco, se interpreta como una cadena de formato numérico personalizado. Para obtener más información, vea Cadenas con formato numérico personalizado. Algunas sobrecargas del método ToString de todos los tipos numéricos admiten las cadenas de formato numérico estándar. Por ejemplo, se puede proporcionar una cadena de formato numérico a los métodos ToString(String, IFormatProvider) y ToString(String) del tipo Int32. La característica de formato compuesto de .NET Framework, que utilizan algunos métodos Write y WriteLine de las clases Console y StreamWriter, el método String..::.Format y el método StringBuilder..::.AppendFormat, admite también cadenas de formato numérico estándar. Sugerencia |
|---|
Puede descargar la utilidad de formato, una aplicación que permite aplicar cadenas de formato a valores numéricos o de fecha y hora y muestra la cadena de resultado. |
En la tabla siguiente se describen los especificadores de formato numérico estándar y se muestran los resultados de ejemplo generados por cada especificador de formato. Vea la sección Notas para obtener información adicional sobre cómo usar las cadenas de formato numérico estándar y la sección Ejemplo para ver una ilustración completa de su uso. Especificador de formato | Nombre | Descripción | Ejemplos |
|---|
"C" o "c" | Currency | Resultado: un valor de divisa. Compatible con: todos los tipos numéricos. Especificador de precisión: número de dígitos decimales. Especificador de precisión predeterminado: definido por System.Globalization..::.NumberFormatInfo. Más información: Especificador de formato de divisa ("C"). | 123.456 ("C", en-US) -> $123.46 123.456 ("C", fr-FR) -> 123,46 € 123.456 ("C", ja-JP) -> ¥123 -123.456 ("C3", en-US) -> ($123.456) -123.456 ("C3", fr-FR) -> -123,456 € -123.456 ("C3", ja-JP) -> -¥123.456 | "D" o "d" | Decimal | Resultado: dígitos enteros con signo negativo opcional. Compatible con: solo tipos integrales. Especificador de precisión: número mínimo de dígitos. Especificador de precisión predeterminado: número mínimo de dígitos necesarios. Más información: Especificador de formato decimal ("D"). | 1234 ("D") -> 1234 -1234 ("D6") -> -001234 | "E" o "e" | Exponencial (científico) | Resultado: notación exponencial. Compatible con: todos los tipos numéricos. Especificador de precisión: número de dígitos decimales. Especificador de precisión predeterminado: 6. Más información: Especificador de formato exponencial ("E"). | 1052.0329112756 ("E", en-US) -> 1.052033E+003 1052.0329112756 ("e", fr-FR) -> 1,052033e+003 -1052.0329112756 ("e2", en-US) -> -1.05e+003 -1052.0329112756 ("E2", fr_FR) -> -1,05E+003 | "F" o "f" | Punto fijo | Resultado: dígitos integrales y decimales con signo negativo opcional. Compatible con: todos los tipos numéricos. Especificador de precisión: número de dígitos decimales. Especificador de precisión predeterminado: definido por System.Globalization..::.NumberFormatInfo. Más información: Especificador de formato de punto fijo ("F"). | 1234.567 ("F", en-US) -> 1234.57 1234.567 ("F", de-DE) -> 1234,57 1234 ("F1", en-US) -> 1234.0 1234 ("F1", de-DE) -> 1234,0 -1234.56 ("F4", en-US) -> -1234.5600 -1234.56 ("F4", de-DE) -> -1234,5600 | "G" o "g" | General | Resultado: notación de punto fijo o científica, la que sea más compacta. Compatible con: todos los tipos numéricos. Especificador de precisión: número de dígitos significativos. Especificador de precisión predeterminado: depende del tipo numérico. Más información: Especificador de formato general ("G"). | -123.456 ("G", en-US) -> -123.456 123.456 ("G", sv-SE) -> -123,456 123.4546 ("G4", en-US) -> 123.5 123.4546 ("G4", sv-SE) -> 123,5 -1.234567890e-25 ("G", en-US) -> -1.23456789E-25 -1.234567890e-25 ("G", sv-SE) -> -1,23456789E-25 | "N" o "n" | Número | Resultado: dígitos integrales y decimales, separadores de grupos y un separador decimal con signo negativo opcional. Compatible con: todos los tipos numéricos. Especificador de precisión: número deseado de decimales. Especificador de precisión predeterminado: definido por System.Globalization..::.NumberFormatInfo. Más información: Especificador de formato numérico ("N"). | 1234.567 ("N", en-US) -> 1,234.57 1234.567 ("N", ru-RU) -> 1 234,57 1234 ("N", en-US) -> 1,234.0 1234 ("N", ru-RU) -> 1 234,0 -1234.56 ("N", en-US) -> -1,234.560 -1234.56 ("N", ru-RU) -> -1 234,560 | "P" o "p" | Percent | Resultado: número multiplicado por 100 y mostrado con un símbolo de porcentaje. Compatible con: todos los tipos numéricos. Especificador de precisión: número deseado de decimales. Especificador de precisión predeterminado: definido por System.Globalization..::.NumberFormatInfo. Más información: Especificador de formato de porcentaje ("P"). | 1 ("P", en-US) -> 100.00 % 1 ("P", fr-FR) -> 100,00 % -0.39678 ("P1", en-US) -> -39.7 % -0.39678 ("P1", fr-FR) -> -39,7 % | "R" o "r" | Acción de ida y vuelta | Resultado: cadena que puede aplicar acciones de ida y vuelta (round-trip) a un número idéntico. Compatible con: Single, Double y BigInteger. Especificador de precisión: se omite. Más información: Especificador de formato de operación de ida y vuelta ("R"). | 123456789.12345678 ("R") -> 123456789.12345678 -1234567890.12345678 ("R") -> -1234567890.1234567 | "X" o "x" | Hexadecimal | Resultado: cadena hexadecimal. Compatible con: solo tipos integrales. Especificador de precisión: número de dígitos en la cadena de resultado. Más información: Especificador de formato hexadecimal ("X"). | 255 ("X") -> FF -1 ("x") -> ff 255 ("x4") -> 00ff -1 ("X4") -> 00FF | Cualquier otro carácter único | Especificador desconocido | Resultado: Produce FormatException en tiempo de ejecución. | |

Usar cadenas de formato numérico estándar
Una cadena de formato numérico estándar se puede usar para definir el formato de un valor numérico de una de dos maneras: Se puede pasar a una sobrecarga del método ToString que tiene un parámetro format. En el ejemplo siguiente se da formato a un valor numérico como una cadena de divisa en la referencia cultural actual (en este caso, en-US).
Dim value As Decimal = 123.456d
Console.WriteLine(value.ToString("C2"))
' Displays $123.46
decimal value = 123.456m;
Console.WriteLine(value.ToString("C2"));
// Displays $123.46
Se puede proporcionar como el parámetro formatString en un elemento de formato usado con métodos como String..::.Format, Console..::.WriteLine y StringBuilder..::.AppendFormat. Para obtener más información, vea Formatos compuestos. En el ejemplo siguiente se usa un elemento de formato para insertar un valor de divisa en una cadena.
Dim value As Decimal = 123.456d
Console.WriteLine("Your account balance is {0:C2}.", value)
' Displays "Your account balance is $123.46."
decimal value = 123.456m;
Console.WriteLine("Your account balance is {0:C2}.", value);
// Displays "Your account balance is $123.46."
En las secciones siguientes se proporciona información detallada sobre cada una de las cadenas de formato numérico estándar.

Especificador de formato de divisa ("C")
El especificador de formato "C" (divisa) convierte un número en una cadena que representa una cantidad de divisa. El especificador de precisión indica el número deseado de posiciones decimales en la cadena de resultado. Si se omite el especificador de precisión, la precisión predeterminada está definida por la propiedad NumberFormatInfo..::.CurrencyDecimalDigits. Si el valor al que se va a dar formato tiene más posiciones decimales que el número especificado o predeterminado, el valor fraccionario se redondea en la cadena de resultado. Si el valor situado a la derecha del número de posiciones decimales especificadas es 5 o superior, el último dígito de la cadena de resultado se redondea desde cero. La información de formato del objeto NumberFormatInfo actual afecta a la cadena de resultado. En la tabla siguiente se enumeran las propiedades de NumberFormatInfo que controlan el formato de la cadena devuelta. En el ejemplo siguiente se da formato a un valor Double con el especificador de formato de divisa.
Dim value As Double = 12345.6789
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture))
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture))
Console.WriteLine(value.ToString("C3", _
CultureInfo.CreateSpecificCulture("da-DK")))
' The example displays the following output on a system whose
' current culture is English (United States):
' $12,345.68
' $12,345.679
' kr 12.345,679
double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3",
CultureInfo.CreateSpecificCulture("da-DK")));
// The example displays the following output on a system whose
// current culture is English (United States):
// $12,345.68
// $12,345.679
// kr 12.345,679
Volver a la tabla

Especificador de formato decimal ("D")
El especificador de formato "D" (o decimal) convierte un número en una cadena de dígitos decimales (0-9), precedida por un signo menos si el número es negativo. Este formato sólo es compatible con los tipos enteros. El especificador de precisión indica el número mínimo de dígitos deseado en la cadena resultante. Si es preciso, el número se rellena con ceros a la izquierda para generar el número de dígitos que aporta el especificador de precisión. Si no se indica ningún especificador de precisión, el valor predeterminado es el valor mínimo necesario para representar el entero sin ceros iniciales. La información de formato del objeto NumberFormatInfo actual afecta a la cadena de resultado. Como se muestra en la tabla siguiente, una única propiedad afecta al formato de la cadena de resultado. Propiedad de NumberFormatInfo | Descripción |
|---|
NegativeSign | Define la cadena que indica que un número es negativo. |
En el ejemplo siguiente se da formato a un valor Int32 con el especificador de formato decimal.
Dim value As Integer
value = 12345
Console.WriteLine(value.ToString("D"))
' Displays 12345
Console.WriteLine(value.ToString("D8"))
' Displays 00012345
value = -12345
Console.WriteLine(value.ToString("D"))
' Displays -12345
Console.WriteLine(value.ToString("D8"))
' Displays -00012345
int value;
value = 12345;
Console.WriteLine(value.ToString("D"));
// Displays 12345
Console.WriteLine(value.ToString("D8"));
// Displays 00012345
value = -12345;
Console.WriteLine(value.ToString("D"));
// Displays -12345
Console.WriteLine(value.ToString("D8"));
// Displays -00012345
Volver a la tabla

Especificador de formato exponencial ("E")
El especificador de formato exponencial ("E") convierte un número en una cadena con el formato "-d.ddd…E+ddd" o "-d.ddd…e+ddd", donde cada "d" indica un dígito (0-9). La cadena comienza con un signo menos si el número es negativo. El separador decimal siempre va precedido por exactamente un dígito. El especificador de precisión indica el número deseado de dígitos después del separador decimal. Si se omite el especificador de precisión, se emplea uno predeterminado que tiene seis dígitos después del separador decimal. El modelo de mayúsculas o minúsculas del especificador de formato indica si se debe prefijar el exponente con una "E" o con una "e". El exponente siempre consta de un signo más o menos y de un mínimo de tres dígitos. El exponente se rellena con ceros para adaptarlo a este mínimo, si es necesario. La información de formato del objeto NumberFormatInfo actual afecta a la cadena de resultado. En la tabla siguiente se enumeran las propiedades de NumberFormatInfo que controlan el formato de la cadena devuelta. Propiedad de NumberFormatInfo | Descripción |
|---|
NegativeSign | Define la cadena que indica que un número es negativo tanto para el coeficiente como para el exponente. | NumberDecimalSeparator | Define la cadena que separa el dígito integral de los dígitos decimales en el coeficiente. | PositiveSign | Define la cadena que indica que un exponente es positivo. |
En el ejemplo siguiente se da formato a un valor Double con el especificador de formato exponencial.
Dim value As Double = 12345.6789
Console.WriteLine(value.ToString("E", CultureInfo.InvariantCulture))
' Displays 1.234568E+004
Console.WriteLine(value.ToString("E10", CultureInfo.InvariantCulture))
' Displays 1.2345678900E+004
Console.WriteLine(value.ToString("e4", CultureInfo.InvariantCulture))
' Displays 1.2346e+004
Console.WriteLine(value.ToString("E", _
CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 1,234568E+004
double value = 12345.6789;
Console.WriteLine(value.ToString("E", CultureInfo.InvariantCulture));
// Displays 1.234568E+004
Console.WriteLine(value.ToString("E10", CultureInfo.InvariantCulture));
// Displays 1.2345678900E+004
Console.WriteLine(value.ToString("e4", CultureInfo.InvariantCulture));
// Displays 1.2346e+004
Console.WriteLine(value.ToString("E",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 1,234568E+004
Volver a la tabla

Especificador de formato de punto fijo ("F")
El especificador de formato de punto fijo ("F) convierte un número en una cadena con el formato "-ddd.ddd…", donde cada "d" indica un dígito (0-9). La cadena comienza con un signo menos si el número es negativo. El especificador de precisión indica el número deseado de cifras decimales. Si se omite el especificador de precisión, la propiedad NumberFormatInfo..::.NumberDecimalDigits actual proporciona la precisión numérica. La información de formato del objeto NumberFormatInfo actual afecta a la cadena de resultado. En la tabla siguiente se enumeran las propiedades del objeto NumberFormatInfo que controlan el formato de la cadena de resultado. Propiedad de NumberFormatInfo | Descripción |
|---|
NegativeSign | Define la cadena que indica que un número es negativo. | NumberDecimalSeparator | Define la cadena que separa los dígitos integrales de los decimales. | NumberDecimalDigits | Define el número predeterminado de dígitos decimales. Este valor puede reemplazarse por el uso del especificador de precisión. |
En el ejemplo siguiente se da formato a un valor Double e Int32 con el especificador de formato de punto fijo.
Dim integerNumber As Integer
integerNumber = 17843
Console.WriteLine(integerNumber.ToString("F", CultureInfo.InvariantCulture))
' Displays 17843.00
integerNumber = -29541
Console.WriteLine(integerNumber.ToString("F3", CultureInfo.InvariantCulture))
' Displays -29541.000
Dim doubleNumber As Double
doubleNumber = 18934.1879
Console.WriteLine(doubleNumber.ToString("F", CultureInfo.InvariantCulture))
' Displays 18934.19
Console.WriteLine(doubleNumber.ToString("F0", CultureInfo.InvariantCulture))
' Displays 18934
doubleNumber = -1898300.1987
Console.WriteLine(doubleNumber.ToString("F1", CultureInfo.InvariantCulture))
' Displays -1898300.2
Console.WriteLine(doubleNumber.ToString("F3", _
CultureInfo.CreateSpecificCulture("es-ES")))
' Displays -1898300,199
int integerNumber;
integerNumber = 17843;
Console.WriteLine(integerNumber.ToString("F",
CultureInfo.InvariantCulture));
// Displays 17843.00
integerNumber = -29541;
Console.WriteLine(integerNumber.ToString("F3",
CultureInfo.InvariantCulture));
// Displays -29541.000
double doubleNumber;
doubleNumber = 18934.1879;
Console.WriteLine(doubleNumber.ToString("F", CultureInfo.InvariantCulture));
// Displays 18934.19
Console.WriteLine(doubleNumber.ToString("F0", CultureInfo.InvariantCulture));
// Displays 18934
doubleNumber = -1898300.1987;
Console.WriteLine(doubleNumber.ToString("F1", CultureInfo.InvariantCulture));
// Displays -1898300.2
Console.WriteLine(doubleNumber.ToString("F3",
CultureInfo.CreateSpecificCulture("es-ES")));
// Displays -1898300,199
Volver a la tabla

Especificador de formato general ("G")
El especificador de formato general ("G") convierte un número a la notación de punto fijo o científica más compacta, dependiendo del tipo del número y de si hay un especificador de precisión o no. El especificador de precisión define el número máximo de dígitos significativos que pueden aparecer en la cadena de resultado. Si el especificador de precisión se omite o es cero, el tipo del número determina la precisión predeterminada, como se indica en la tabla siguiente. La notación de punto fijo se utiliza si el exponente que resultaría de la expresión del número en notación científica es mayor que -5 y menor que el especificador de precisión, de lo contrario se utiliza la notación científica. El resultado contiene un separador decimal si es necesario y se omiten los ceros finales después de ese separador. Si el especificador de precisión está presente y el número de dígitos significativos del resultado supera la precisión especificada, los dígitos finales sobrantes se quitan mediante redondeo. Sin embargo, si el número es Decimal y se omite el especificador de precisión, siempre se usa la notación de punto fijo y se conservan los ceros finales. Si se usa la notación científica, el exponente del resultado lleva el prefijo "E" si el especificador de formato es "G", o "e" si el especificador de formato es "g". El exponente contiene un mínimo de dos dígitos. Esto difiere del formato para la notación científica que genera el especificador de formato exponencial, que incluye un mínimo de tres dígitos en el exponente. La información de formato del objeto NumberFormatInfo actual afecta a la cadena de resultado. En la tabla siguiente se enumeran las propiedades de NumberFormatInfo que controlan el formato de la cadena de resultado. Propiedad de NumberFormatInfo | Descripción |
|---|
NegativeSign | Define la cadena que indica que un número es negativo. | NumberDecimalSeparator | Define la cadena que separa los dígitos integrales de los decimales. | NumberDecimalDigits | Define el número predeterminado de dígitos decimales. Este valor puede reemplazarse por el uso del especificador de precisión. | PositiveSign | Define la cadena que indica que un exponente es positivo. |
En el ejemplo siguiente se da formato a valores de punto flotante ordenados con el especificador de formato general.
Dim number As Double
number = 12345.6789
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture))
' Displays 12345.6789
Console.WriteLine(number.ToString("G", _
CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 12345,6789
Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture))
' Displays 12345.68
number = .0000023
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture))
' Displays 2.3E-06
Console.WriteLine(number.ToString("G", _
CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 2,3E-06
number = .0023
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture))
' Displays 0.0023
number = 1234
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture))
' Displays 1.2E+03
number = Math.Pi
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture))
' Displays 3.1416
double number;
number = 12345.6789;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 12345.6789
Console.WriteLine(number.ToString("G",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 12345,6789
Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture));
// Displays 12345.68
number = .0000023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 2.3E-06
Console.WriteLine(number.ToString("G",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 2,3E-06
number = .0023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 0.0023
number = 1234;
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));
// Displays 1.2E+03
number = Math.PI;
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));
// Displays 3.1416
Volver a la tabla

Especificador de formato numérico ("N")
El especificador de formato numérico ("N") convierte un número en una cadena con el formato "-d,ddd,ddd.ddd…", donde "-" indica el símbolo de número negativo, si es necesario; "d", representa cada dígito (0-9); "," es el separador de grupo; y "." es el símbolo de punto decimal. El especificador de precisión indica el número deseado de dígitos después del separador decimal. Si se omite el especificador de precisión, el número de posiciones decimales está definido por la propiedad NumberFormatInfo..::.NumberDecimalDigits actual. La información de formato del objeto NumberFormatInfo actual afecta a la cadena de resultado. En la tabla siguiente se enumeran las propiedades de NumberFormatInfo que controlan el formato de la cadena de resultado. Propiedad de NumberFormatInfo | Descripción |
|---|
NegativeSign | Define la cadena que indica que un número es negativo. | NumberNegativePattern | Define el formato de los valores negativos y especifica si el signo negativo se representa mediante paréntesis o por la propiedad NegativeSign. | NumberGroupSizes | Define el número de dígitos enteros que aparecen entre los separadores de grupos. | NumberGroupSeparator | Define la cadena que separa los grupos de números integrales. | NumberDecimalSeparator | Define la cadena que separa los dígitos integrales y decimales. | NumberDecimalDigits | Define el número predeterminado de dígitos decimales. Este valor puede reemplazarse por el uso de un especificador de precisión. |
En el ejemplo siguiente se da formato a valores de punto flotante ordenados con el especificador de formato numérico.
Dim dblValue As Double = -12445.6789
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture))
' Displays -12,445.68
Console.WriteLine(dblValue.ToString("N1", _
CultureInfo.CreateSpecificCulture("sv-SE")))
' Displays -12 445,7
Dim intValue As Integer = 123456789
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture))
' Displays 123,456,789.0
double dblValue = -12445.6789;
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture));
// Displays -12,445.68
Console.WriteLine(dblValue.ToString("N1",
CultureInfo.CreateSpecificCulture("sv-SE")));
// Displays -12 445,7
int intValue = 123456789;
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture));
// Displays 123,456,789.0
Volver a la tabla

Especificador de formato de porcentaje ("P")
El especificador de formato de porcentaje ("P") multiplica un número por 100 y lo convierte en una cadena que representa un porcentaje. El especificador de precisión indica el número deseado de cifras decimales. Si se omite el especificador de precisión, se usará la precisión numérica predeterminada proporcionada por la propiedad PercentDecimalDigits actual. En la tabla siguiente se enumeran las propiedades de NumberFormatInfo que controlan el formato de la cadena devuelta. Propiedad de NumberFormatInfo | Descripción |
|---|
PercentPositivePattern | Define la posición del símbolo de porcentaje para los valores positivos. | PercentNegativePattern | Define la posición del símbolo de porcentaje y del símbolo negativo para los valores negativos. | NegativeSign | Define la cadena que indica que un número es negativo. | PercentSymbol | Define el símbolo de porcentaje. | PercentDecimalDigits | Define el número predeterminado de dígitos decimales en un valor de porcentaje. Este valor puede reemplazarse por el uso del especificador de precisión. | PercentDecimalSeparator | Define la cadena que separa los dígitos integrales y decimales. | PercentGroupSeparator | Define la cadena que separa los grupos de números integrales. | PercentGroupSizes | Define el número de dígitos enteros que aparecen en un grupo. |
En el ejemplo siguiente se da formato a valores de punto flotante con el especificador de formato de porcentaje.
Dim number As Double = .2468013
Console.WriteLine(number.ToString("P", CultureInfo.InvariantCulture))
' Displays 24.68 %
Console.WriteLine(number.ToString("P", _
CultureInfo.CreateSpecificCulture("hr-HR")))
' Displays 24,68%
Console.WriteLine(number.ToString("P1", CultureInfo.InvariantCulture))
' Displays 24.7 %
double number = .2468013;
Console.WriteLine(number.ToString("P", CultureInfo.InvariantCulture));
// Displays 24.68 %
Console.WriteLine(number.ToString("P",
CultureInfo.CreateSpecificCulture("hr-HR")));
// Displays 24,68%
Console.WriteLine(number.ToString("P1", CultureInfo.InvariantCulture));
// Displays 24.7 %
Volver a la tabla

Especificador de formato de operación de ida y vuelta ("R")
El especificador de formato de operación de ida y vuelta ("R") garantiza que un valor numérico que se convierte en una cadena volverá a tomar el mismo valor numérico. Este formato solo es compatible para los tipos Single, Double y BigInteger. Cuando se da formato a un valor BigInteger mediante este especificador, su representación de cadena contiene todos los dígitos significativos del valor BigInteger. Cuando se da formato a un valor Single o Double mediante este especificador, primero se comprueba empleando el formato general, con 15 dígitos de precisión para un tipo Double y 7 dígitos de precisión para un tipo Single. Si el valor recupera correctamente el mismo valor numérico al analizarse, se le aplica formato mediante el especificador de formato general. Si el valor no recupera correctamente el mismo valor numérico, se le da formato usando 17 dígitos de precisión para un tipo Double y 9 para un tipo Single. Aunque puede incluir un especificador de precisión, se omite. Los especificadores de ida y vuelta tienen prioridad sobre la precisión al utilizar este especificador. La información de formato del objeto NumberFormatInfo actual afecta a la cadena de resultado. En la tabla siguiente se enumeran las propiedades de NumberFormatInfo que controlan el formato de la cadena de resultado. Propiedad de NumberFormatInfo | Descripción |
|---|
NegativeSign | Define la cadena que indica que un número es negativo. | NumberDecimalSeparator | Define la cadena que separa los dígitos integrales de los decimales. | PositiveSign | Define la cadena que indica que un exponente es positivo. |
En el ejemplo siguiente se da formato a valores Double con el especificador de formato de ida y vuelta.
Dim value As Double
value = Math.Pi
Console.WriteLine(value.ToString("r"))
' Displays 3.1415926535897931
Console.WriteLine(value.ToString("r", _
CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 3,1415926535897931
value = 1.623e-21
Console.WriteLine(value.ToString("r"))
' Displays 1.623E-21
double value;
value = Math.PI;
Console.WriteLine(value.ToString("r"));
// Displays 3.1415926535897931
Console.WriteLine(value.ToString("r",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 3,1415926535897931
value = 1.623e-21;
Console.WriteLine(value.ToString("r"));
// Displays 1.623E-21
Volver a la tabla

Especificador de formato hexadecimal ("X")
El especificador de formato hexadecimal ("X") convierte un número en una cadena de dígitos hexadecimales. El modelo de mayúsculas y minúsculas del especificador de formato indica si se van a usar caracteres en mayúsculas o en minúsculas para los dígitos hexadecimales mayores de 9. Por ejemplo, use "X" para generar "ABCDEF" y "x" para generar "abcdef". Este formato sólo es compatible con los tipos enteros. El especificador de precisión indica el número mínimo de dígitos deseado en la cadena resultante. Si es preciso, el número se rellena con ceros a la izquierda para generar el número de dígitos que aporta el especificador de precisión. La información de formato del objeto NumberFormatInfo actual no afecta a la cadena de resultado. En el ejemplo siguiente se da formato a valores Int32 con el especificador de formato hexadecimal.
Dim value As Integer
value = &h2045e
Console.WriteLine(value.ToString("x"))
' Displays 2045e
Console.WriteLine(value.ToString("X"))
' Displays 2045E
Console.WriteLine(value.ToString("X8"))
' Displays 0002045E
value = 123456789
Console.WriteLine(value.ToString("X"))
' Displays 75BCD15
Console.WriteLine(value.ToString("X2"))
' Displays 75BCD15
int value;
value = 0x2045e;
Console.WriteLine(value.ToString("x"));
// Displays 2045e
Console.WriteLine(value.ToString("X"));
// Displays 2045E
Console.WriteLine(value.ToString("X8"));
// Displays 0002045E
value = 123456789;
Console.WriteLine(value.ToString("X"));
// Displays 75BCD15
Console.WriteLine(value.ToString("X2"));
// Displays 75BCD15
Volver a la tabla

Notas
Configuración del Panel de controlLos valores de configuración del elemento Configuración regional y de idioma del Panel de control influyen en la cadena de resultado generada por una operación de formato. Esas configuraciones se usan para inicializar el objeto NumberFormatInfo asociado a la referencia cultural del subproceso actual, que proporciona valores que se usan para controlar el formato. Los equipos que usan configuraciones diferentes generarán cadenas de resultado distintas. Asimismo, si se utiliza el constructor CultureInfo..::.CultureInfo(String) para crear instancias de un nuevo objeto CultureInfo que representa la misma referencia cultural que la referencia cultural del sistema actual, cualquier personalización establecida por el elemento Configuración regional y de idioma del Panel de control se aplicará al nuevo objeto CultureInfo. Puede usar el constructor CultureInfo..::.CultureInfo(String, Boolean) para crear un objeto CultureInfo que no refleje las personalizaciones de un sistema. Propiedades NumberFormatInfoEl formato se ve influenciado por las propiedades del objeto NumberFormatInfo actual, proporcionado implícitamente por la referencia cultural del subproceso actual o explícitamente por el parámetro IFormatProvider del método que invoca el formato. Especifique un objeto NumberFormatInfo o CultureInfo para dicho parámetro. Tipos numéricos enteros y de punto flotanteInfinitos de punto flotante y NaN

Ejemplo
En el ejemplo siguiente se da formato a un valor numérico integral y de punto flotante mediante la referencia cultural en-US y todos los especificadores de formato numérico estándar. En este ejemplo se usan dos tipos numéricos concretos (Double y Int32), pero se obtendrían resultados similares con cualquiera de los demás tipos numéricos base (Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, BigInteger, Decimal y Single).
Option Strict On
Imports System.Globalization
Imports System.Threading
Module NumericFormats
Public Sub Main()
' Display string representations of numbers for en-us culture
Dim ci As New CultureInfo("en-us")
' Output floating point values
Dim floating As Double = 10761.937554
Console.WriteLine("C: {0}", _
floating.ToString("C", ci)) ' Displays "C: $10,761.94"
Console.WriteLine("E: {0}", _
floating.ToString("E03", ci)) ' Displays "E: 1.076E+004"
Console.WriteLine("F: {0}", _
floating.ToString("F04", ci)) ' Displays "F: 10761.9376"
Console.WriteLine("G: {0}", _
floating.ToString("G", ci)) ' Displays "G: 10761.937554"
Console.WriteLine("N: {0}", _
floating.ToString("N03", ci)) ' Displays "N: 10,761.938"
Console.WriteLine("P: {0}", _
(floating/10000).ToString("P02", ci)) ' Displays "P: 107.62 %"
Console.WriteLine("R: {0}", _
floating.ToString("R", ci)) ' Displays "R: 10761.937554"
Console.WriteLine()
' Output integral values
Dim integral As Integer = 8395
Console.WriteLine("C: {0}", _
integral.ToString("C", ci)) ' Displays "C: $8,395.00"
Console.WriteLine("D: {0}", _
integral.ToString("D6")) ' Displays "D: 008395"
Console.WriteLine("E: {0}", _
integral.ToString("E03", ci)) ' Displays "E: 8.395E+003"
Console.WriteLine("F: {0}", _
integral.ToString("F01", ci)) ' Displays "F: 8395.0"
Console.WriteLine("G: {0}", _
integral.ToString("G", ci)) ' Displays "G: 8395"
Console.WriteLine("N: {0}", _
integral.ToString("N01", ci)) ' Displays "N: 8,395.0"
Console.WriteLine("P: {0}", _
(integral/10000).ToString("P02", ci)) ' Displays "P: 83.95 %"
Console.WriteLine("X: 0x{0}", _
integral.ToString("X", ci)) ' Displays "X: 0x20CB"
Console.WriteLine()
End Sub
End Module
using System;
using System.Globalization;
using System.Threading;
public class NumericFormats
{
public static void Main()
{
// Display string representations of numbers for en-us culture
CultureInfo ci = new CultureInfo("en-us");
// Output floating point values
double floating = 10761.937554;
Console.WriteLine("C: {0}",
floating.ToString("C", ci)); // Displays "C: $10,761.94"
Console.WriteLine("E: {0}",
floating.ToString("E03", ci)); // Displays "E: 1.076E+004"
Console.WriteLine("F: {0}",
floating.ToString("F04", ci)); // Displays "F: 10761.9376"
Console.WriteLine("G: {0}",
floating.ToString("G", ci)); // Displays "G: 10761.937554"
Console.WriteLine("N: {0}",
floating.ToString("N03", ci)); // Displays "N: 10,761.938"
Console.WriteLine("P: {0}",
(floating/10000).ToString("P02", ci)); // Displays "P: 107.62 %"
Console.WriteLine("R: {0}",
floating.ToString("R", ci)); // Displays "R: 10761.937554"
Console.WriteLine();
// Output integral values
int integral = 8395;
Console.WriteLine("C: {0}",
integral.ToString("C", ci)); // Displays "C: $8,395.00"
Console.WriteLine("D: {0}",
integral.ToString("D6", ci)); // Displays "D: 008395"
Console.WriteLine("E: {0}",
integral.ToString("E03", ci)); // Displays "E: 8.395E+003"
Console.WriteLine("F: {0}",
integral.ToString("F01", ci)); // Displays "F: 8395.0"
Console.WriteLine("G: {0}",
integral.ToString("G", ci)); // Displays "G: 8395"
Console.WriteLine("N: {0}",
integral.ToString("N01", ci)); // Displays "N: 8,395.0"
Console.WriteLine("P: {0}",
(integral/10000.0).ToString("P02", ci)); // Displays "P: 83.95 %"
Console.WriteLine("X: 0x{0}",
integral.ToString("X", ci)); // Displays "X: 0x20CB"
Console.WriteLine();
}
}

Vea también
TareasReferenciaConceptos

Historial de cambios
Fecha | Historial | Motivo |
|---|
Marzo de 2011
| Agregado un vínculo a la utilidad de formato. |
Mejora de la información.
|
Julio de 2010
| Se ha indicado que con la cadena de formato estándar "C" se usa el redondeo desde cero. |
Comentarios de los clientes.
|
|