Partilhar via


Standard Numeric Format Strings 

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.

The following table describes the standard numeric format specifiers. For examples of the output produced by each format specifier, see Standard Numeric Format Strings Output Examples. For more information, see the notes that follow the table.

Format specifier Name Description

C or c

Currency

The number is converted to a string that represents a currency amount. The conversion is controlled by the currency format information of the current NumberFormatInfo object.

The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default currency precision given by the current NumberFormatInfo object.

D or d

Decimal

This format is supported only for integral types. The number is converted to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative.

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.

E or e

Scientific (exponential)

The number is converted 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. 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.

F or f

Fixed-point

The number is converted 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 default numeric precision given by the current NumberFormatInfo object.

G or g

General

The number is converted 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. If the precision specifier is omitted or zero, the type of the number determines the default precision, as indicated by the following list.

  • Byte or SByte: 3

  • Int16 or UInt16: 5

  • Int32 or UInt32: 10

  • Int64 or UInt64: 19

  • Single: 7

  • Double: 15

  • Decimal: 29

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 zeroes are omitted. If the precision specifier is present and the number of significant digits in the result exceeds the specified precision, then the excess trailing digits are removed by rounding.

The exception to the preceding rule is if the number is a Decimal and the precision specifier is omitted. In that case, fixed-point notation is always used and trailing zeroes 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'.

N or n

Number

The number is converted 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 thousand separator between number groups, and '.' indicates a decimal point symbol. The actual negative number pattern, number group size, thousand separator, and decimal separator are specified by the current NumberFormatInfo object.

The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by the current NumberFormatInfo object.

P or p

Percent

The number is converted to a string that represents a percent as defined by the NumberFormatInfo.PercentNegativePattern property if the number is negative, or the NumberFormatInfo.PercentPositivePattern property if the number is positive. The converted number is multiplied by 100 in order to be presented as a percentage.

The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by the current NumberFormatInfo object.

R or r

Round-trip

This format is supported only for the Single and Double types. The round-trip specifier guarantees that a numeric value converted to a string will be parsed back into the same numeric value. When a numeric value is formatted using this specifier, it is first tested using the general format, with 15 spaces of precision for a Double and 7 spaces 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. However, if the value is not successfully parsed back to the same numeric value, then the value is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single.

Although a precision specifier can present, it is ignored. Round trips are given precedence over precision when using this specifier.

X or x

Hexadecimal

This format is supported only for integral types. The number is converted to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for the hexadecimal digits greater than 9. For example, use 'X' to produce "ABCDEF", and 'x' to produce "abcdef".

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.

Any other single character

(Unknown specifier)

(An unknown specifier throws a runtime format exception.)

Notes

Control Panel Settings

The 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, and the current thread culture provides values used to govern formatting. Computers using different settings will generate different result strings.

NumberFormatInfo Properties

Formatting is influenced by 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 Types

Some 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, and UInt64. The floating-point numeric types are Decimal, Single, and Double.

Floating-Point Infinities and NaN

Note that regardless of the format string, if the value of a Single or Double floating-point type is positive infinity, negative infinity, or Not a Number (NaN), the formatted string is the value of the respective PositiveInfinitySymbol, NegativeInfinitySymbol, or NaNSymbol property specified by the currently applicable NumberFormatInfo object.

Example

The following code example formats an integral and a floating-point numeric value using the thread current culture, a specified culture, and all the standard numeric format specifiers. This code example uses two particular numeric types, but would yield similar results for any of the numeric base types (Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Decimal, Single, and Double).

' This code example demonstrates the ToString(String) and 
' ToString(String, IFormatProvider) methods for integral and
' floating-point numbers, in conjunction with the standard 
' numeric format specifiers.
' This code example uses the System.Int32 integral type and 
' the System.Double floating-point type, but would yield 
' similar results for any of the numeric types. The integral 
' numeric types are System.Byte, SByte, Int16, Int32, Int64, 
' UInt16, UInt32, and UInt64. The floating-point numeric types 
' are Decimal, Single, and Double.

Imports System
Imports System.Globalization
Imports System.Threading

Class Sample
    Public Shared Sub Main() 
        ' Format a negative integer or floating-point number in various ways.
        Dim integralVal As Integer = -12345
        Dim floatingVal As Double  = -1234.567
        
        Dim msgCurrency As String =    "(C) Currency: . . . . . . "
        Dim msgDecimal As String =     "(D) Decimal:. . . . . . . "
        Dim msgScientific As String =  "(E) Scientific: . . . . . "
        Dim msgFixedPoint As String =  "(F) Fixed point:. . . . . "
        Dim msgGeneral As String =     "(G) General (default):. . "
        Dim msgNumber As String =      "(N) Number: . . . . . . . "
        Dim msgPercent As String =     "(P) Percent:. . . . . . . "
        Dim msgRoundTrip As String =   "(R) Round-trip: . . . . . "
        Dim msgHexadecimal As String = "(X) Hexadecimal:. . . . . "
        
        Dim msg1 As String = "Use ToString(String) and the current thread culture." + vbLf
        Dim msg2 As String = "Use ToString(String, IFormatProvider) and a specified culture." + vbLf
        Dim msgCulture As String = "Culture:"
        Dim msgIntegralVal As String = "Integral value:"
        Dim msgFloatingVal As String = "Floating-point value:"
        
        Dim ci As CultureInfo
        '
        Console.Clear()
        Console.WriteLine("Standard Numeric Format Specifiers:" & vbLf)
        ' Display the values.
        Console.WriteLine(msg1)
        
        ' Display the thread current culture, which is used to format the values.
        ci = Thread.CurrentThread.CurrentCulture
        Console.WriteLine("{0,-26}{1}", msgCulture, ci.DisplayName)
        
        ' Display the integral and floating-point values.
        Console.WriteLine("{0,-26}{1}", msgIntegralVal, integralVal)
        Console.WriteLine("{0,-26}{1}", msgFloatingVal, floatingVal)
        Console.WriteLine()
        
        ' Use the format specifiers that are only for integral types.
        Console.WriteLine("Format specifiers only for integral types:")
        Console.WriteLine(msgDecimal     & integralVal.ToString("D"))
        Console.WriteLine(msgHexadecimal & integralVal.ToString("X"))
        Console.WriteLine()
        
        ' Use the format specifier that is only for the Single and Double 
        ' floating-point types.
        Console.WriteLine("Format specifier only for the Single and Double types:")
        Console.WriteLine(msgRoundTrip   & floatingVal.ToString("R"))
        Console.WriteLine()
        
        ' Use the format specifiers that are for integral or floating-point types.
        Console.WriteLine("Format specifiers for integral or floating-point types:")
        Console.WriteLine(msgCurrency    & floatingVal.ToString("C"))
        Console.WriteLine(msgScientific  & floatingVal.ToString("E"))
        Console.WriteLine(msgFixedPoint  & floatingVal.ToString("F"))
        Console.WriteLine(msgGeneral     & floatingVal.ToString("G"))
        Console.WriteLine(msgNumber      & floatingVal.ToString("N"))
        Console.WriteLine(msgPercent     & floatingVal.ToString("P"))
        Console.WriteLine()
        
        ' Display the same values using a CultureInfo object. The CultureInfo class 
        ' implements IFormatProvider.
        Console.WriteLine(msg2)
        
        ' Display the culture used to format the values. 
        ' Create a European culture and change its currency symbol to "euro" because 
        ' this particular code example uses a thread current UI culture that cannot 
        ' display the euro symbol (€).
        ci = New CultureInfo("de-DE")
        ci.NumberFormat.CurrencySymbol = "euro"
        Console.WriteLine("{0,-26}{1}", msgCulture, ci.DisplayName)
        
        ' Display the integral and floating-point values.
        Console.WriteLine("{0,-26}{1}", msgIntegralVal, integralVal)
        Console.WriteLine("{0,-26}{1}", msgFloatingVal, floatingVal)
        Console.WriteLine()
        
        ' Use the format specifiers that are only for integral types.
        Console.WriteLine("Format specifiers only for integral types:")
        Console.WriteLine(msgDecimal     & integralVal.ToString("D", ci))
        Console.WriteLine(msgHexadecimal & integralVal.ToString("X", ci))
        Console.WriteLine()
        
        ' Use the format specifier that is only for the Single and Double 
        ' floating-point types.
        Console.WriteLine("Format specifier only for the Single and Double types:")
        Console.WriteLine(msgRoundTrip   & floatingVal.ToString("R", ci))
        Console.WriteLine()
        
        ' Use the format specifiers that are for integral or floating-point types.
        Console.WriteLine("Format specifiers for integral or floating-point types:")
        Console.WriteLine(msgCurrency    & floatingVal.ToString("C", ci))
        Console.WriteLine(msgScientific  & floatingVal.ToString("E", ci))
        Console.WriteLine(msgFixedPoint  & floatingVal.ToString("F", ci))
        Console.WriteLine(msgGeneral     & floatingVal.ToString("G", ci))
        Console.WriteLine(msgNumber      & floatingVal.ToString("N", ci))
        Console.WriteLine(msgPercent     & floatingVal.ToString("P", ci))
        Console.WriteLine()
    End Sub 'Main
End Class 'Sample
'
'This code example produces the following results:
'
'Standard Numeric Format Specifiers:
'
'Use ToString(String) and the current thread culture.
'
'Culture:                  English (United States)
'Integral value:           -12345
'Floating-point value:     -1234.567
'
'Format specifiers only for integral types:
'(D) Decimal:. . . . . . . -12345
'(X) Hexadecimal:. . . . . FFFFCFC7
'
'Format specifier only for the Single and Double types:
'(R) Round-trip: . . . . . -1234.567
'
'Format specifiers for integral or floating-point types:
'(C) Currency: . . . . . . ($1,234.57)
'(E) Scientific: . . . . . -1.234567E+003
'(F) Fixed point:. . . . . -1234.57
'(G) General (default):. . -1234.567
'(N) Number: . . . . . . . -1,234.57
'(P) Percent:. . . . . . . -123,456.70 %
'
'Use ToString(String, IFormatProvider) and a specified culture.
'
'Culture:                  German (Germany)
'Integral value:           -12345
'Floating-point value:     -1234.567
'
'Format specifiers only for integral types:
'(D) Decimal:. . . . . . . -12345
'(X) Hexadecimal:. . . . . FFFFCFC7
'
'Format specifier only for the Single and Double types:
'(R) Round-trip: . . . . . -1234,567
'
'Format specifiers for integral or floating-point types:
'(C) Currency: . . . . . . -1.234,57 euro
'(E) Scientific: . . . . . -1,234567E+003
'(F) Fixed point:. . . . . -1234,57
'(G) General (default):. . -1234,567
'(N) Number: . . . . . . . -1.234,57
'(P) Percent:. . . . . . . -123.456,70%
'
// This code example demonstrates the ToString(String) and 
// ToString(String, IFormatProvider) methods for integral and
// floating-point numbers, in conjunction with the standard 
// numeric format specifiers.
// This code example uses the System.Int32 integral type and 
// the System.Double floating-point type, but would yield 
// similar results for any of the numeric types. The integral 
// numeric types are System.Byte, SByte, Int16, Int32, Int64, 
// UInt16, UInt32, and UInt64. The floating-point numeric types 
// are Decimal, Single, and Double.

using System;
using System.Globalization;
using System.Threading;

class Sample 
{
    public static void Main() 
    {
// Format a negative integer or floating-point number in various ways.
    int    integralVal = -12345;
    double floatingVal = -1234.567d;

    string msgCurrency =    "(C) Currency: . . . . . . ";
    string msgDecimal  =    "(D) Decimal:. . . . . . . ";
    string msgScientific =  "(E) Scientific: . . . . . ";
    string msgFixedPoint =  "(F) Fixed point:. . . . . ";
    string msgGeneral =     "(G) General (default):. . ";
    string msgNumber =      "(N) Number: . . . . . . . ";
    string msgPercent =     "(P) Percent:. . . . . . . ";
    string msgRoundTrip =   "(R) Round-trip: . . . . . ";
    string msgHexadecimal = "(X) Hexadecimal:. . . . . ";

    string msg1 = "Use ToString(String) and the current thread culture.\n";
    string msg2 = "Use ToString(String, IFormatProvider) and a specified culture.\n";
    string msgCulture     = "Culture:";
    string msgIntegralVal = "Integral value:";
    string msgFloatingVal = "Floating-point value:";

    CultureInfo ci;
//
    Console.Clear();
    Console.WriteLine("Standard Numeric Format Specifiers:\n");
// Display the values.
    Console.WriteLine(msg1);

// Display the thread current culture, which is used to format the values.
    ci = Thread.CurrentThread.CurrentCulture;
    Console.WriteLine("{0,-26}{1}", msgCulture, ci.DisplayName);

// Display the integral and floating-point values.
    Console.WriteLine("{0,-26}{1}", msgIntegralVal, integralVal);
    Console.WriteLine("{0,-26}{1}", msgFloatingVal, floatingVal);
    Console.WriteLine();

// Use the format specifiers that are only for integral types.
    Console.WriteLine("Format specifiers only for integral types:");
    Console.WriteLine(msgDecimal     + integralVal.ToString("D"));
    Console.WriteLine(msgHexadecimal + integralVal.ToString("X"));
    Console.WriteLine();

// Use the format specifier that is only for the Single and Double 
// floating-point types.
    Console.WriteLine("Format specifier only for the Single and Double types:");
    Console.WriteLine(msgRoundTrip   + floatingVal.ToString("R"));
    Console.WriteLine();

// Use the format specifiers that are for integral or floating-point types.
    Console.WriteLine("Format specifiers for integral or floating-point types:");
    Console.WriteLine(msgCurrency    + floatingVal.ToString("C"));
    Console.WriteLine(msgScientific  + floatingVal.ToString("E"));
    Console.WriteLine(msgFixedPoint  + floatingVal.ToString("F"));
    Console.WriteLine(msgGeneral     + floatingVal.ToString("G"));
    Console.WriteLine(msgNumber      + floatingVal.ToString("N"));
    Console.WriteLine(msgPercent     + floatingVal.ToString("P"));
    Console.WriteLine();

// Display the same values using a CultureInfo object. The CultureInfo class 
// implements IFormatProvider.
    Console.WriteLine(msg2);

// Display the culture used to format the values. 
// Create a European culture and change its currency symbol to "euro" because 
// this particular code example uses a thread current UI culture that cannot 
// display the euro symbol (€).
    ci = new CultureInfo("de-DE");
    ci.NumberFormat.CurrencySymbol = "euro";
    Console.WriteLine("{0,-26}{1}", msgCulture, ci.DisplayName);

// Display the integral and floating-point values.
    Console.WriteLine("{0,-26}{1}", msgIntegralVal, integralVal);
    Console.WriteLine("{0,-26}{1}", msgFloatingVal, floatingVal);
    Console.WriteLine();

// Use the format specifiers that are only for integral types.
    Console.WriteLine("Format specifiers only for integral types:");
    Console.WriteLine(msgDecimal     + integralVal.ToString("D", ci));
    Console.WriteLine(msgHexadecimal + integralVal.ToString("X", ci));
    Console.WriteLine();

// Use the format specifier that is only for the Single and Double 
// floating-point types.
    Console.WriteLine("Format specifier only for the Single and Double types:");
    Console.WriteLine(msgRoundTrip   + floatingVal.ToString("R", ci));
    Console.WriteLine();

// Use the format specifiers that are for integral or floating-point types.
    Console.WriteLine("Format specifiers for integral or floating-point types:");
    Console.WriteLine(msgCurrency    + floatingVal.ToString("C", ci));
    Console.WriteLine(msgScientific  + floatingVal.ToString("E", ci));
    Console.WriteLine(msgFixedPoint  + floatingVal.ToString("F", ci));
    Console.WriteLine(msgGeneral     + floatingVal.ToString("G", ci));
    Console.WriteLine(msgNumber      + floatingVal.ToString("N", ci));
    Console.WriteLine(msgPercent     + floatingVal.ToString("P", ci));
    Console.WriteLine();
    }
}
/*
This code example produces the following results:

Standard Numeric Format Specifiers:

Use ToString(String) and the current thread culture.

Culture:                  English (United States)
Integral value:           -12345
Floating-point value:     -1234.567

Format specifiers only for integral types:
(D) Decimal:. . . . . . . -12345
(X) Hexadecimal:. . . . . FFFFCFC7

Format specifier only for the Single and Double types:
(R) Round-trip: . . . . . -1234.567

Format specifiers for integral or floating-point types:
(C) Currency: . . . . . . ($1,234.57)
(E) Scientific: . . . . . -1.234567E+003
(F) Fixed point:. . . . . -1234.57
(G) General (default):. . -1234.567
(N) Number: . . . . . . . -1,234.57
(P) Percent:. . . . . . . -123,456.70 %

Use ToString(String, IFormatProvider) and a specified culture.

Culture:                  German (Germany)
Integral value:           -12345
Floating-point value:     -1234.567

Format specifiers only for integral types:
(D) Decimal:. . . . . . . -12345
(X) Hexadecimal:. . . . . FFFFCFC7

Format specifier only for the Single and Double types:
(R) Round-trip: . . . . . -1234,567

Format specifiers for integral or floating-point types:
(C) Currency: . . . . . . -1.234,57 euro
(E) Scientific: . . . . . -1,234567E+003
(F) Fixed point:. . . . . -1234,57
(G) General (default):. . -1234,567
(N) Number: . . . . . . . -1.234,57
(P) Percent:. . . . . . . -123.456,70%

*/

See Also

Reference

NumberFormatInfo

Concepts

Numeric Format Strings
Standard Numeric Format Strings Output Examples
Custom Numeric Format Strings

Other Resources

Formatting Types