標準數值格式字串Standard Numeric Format Strings

標準數值格式字串會用來格式化一般數字類型。Standard numeric format strings are used to format common numeric types. 標準數值格式字串會採用 Axx 格式,其中:A standard numeric format string takes the form Axx, where:

  • A 是稱為「格式規範」的單一字母字元。A is a single alphabetic character called the format specifier. 任何包含一個以上字母字元 (包含泛空白字元 (White Space)) 的數值格式字串都會解譯為自訂數值格式字串。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.

  • xx 是稱為「精確度規範」的選用性整數。xx is an optional integer called the precision specifier. 精確度規範的範圍從 0 到 99,而且會影響結果內的位數。The precision specifier ranges from 0 to 99 and affects the number of digits in the result. 請注意,精確度規範可控制數字字串表示法中的位數。Note that the precision specifier controls the number of digits in the string representation of a number. 它不會捨入數字本身。It does not round the number itself. 若要執行捨入運算,請使用 Math.CeilingMath.FloorMath.Round 方法。To perform a rounding operation, use the Math.Ceiling, Math.Floor, or Math.Round method.

    當「有效位數規範」控制結果字串中小數點後的位數,結果字串會反映已四捨五入為最接近無限精確度之可代表結果的數字。When precision specifier controls the number of fractional digits in the result string, the result string reflects a number that is rounded to a representable result nearest to the infinitely precise result. 若有兩個相等的近似可代表結果:If there are two equally near representable results:

    • 在 .NET Framework 與 .NET Core (最高版本 .NET Core 2.0) 上,執行階段會選取具有較大之最不顯著位數 (亦即,使用 MidpointRounding.AwayFromZero) 的結果。On the .NET Framework and .NET Core up to .NET Core 2.0, the runtime selects the result with the greater least significant digit (that is, using MidpointRounding.AwayFromZero).
    • 在 .NET Core 2.1 與更新版本上,執行階段會選取具有偶數最不顯著位數 (亦即,使用 MidpointRounding.ToEven) 的結果。On .NET Core 2.1 and later, the runtime selects the result with an even least significant digit (that is, using MidpointRounding.ToEven).

    注意

    有效位數規範可判斷結果字串中的位數。The precision specifier determines the number of digits in the result string. 若要使用前置或尾端空格填補結果字串,請使用複合格式設定功能,並在格式項目中定義「對齊元件」。To pad a result string with leading or trailing spaces, use the composite formatting feature and define an alignment component in the format item.

標準數值格式字串受到下列各項支援:Standard numeric format strings are supported by:

提示

您可以下載格式化公用程式,這個 .NET Core Windows Forms 應用程式可讓您將格式字串套用至數值或日期和時間值,並顯示結果字串。You can download the Formatting Utility, a .NET Core Windows Forms application that lets you apply format strings to either numeric or date and time values and displays the result string. 提供 C#Visual Basic 的原始程式碼。Source code is available for C# and Visual Basic.

下表描述標準數值格式規範,並顯示每個格式範例所產生的範例輸出。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" 或 "c""C" or "c" 貨幣Currency 結果:貨幣值。Result: A currency value.

支援下列項目:所有數值類型。Supported by: All numeric types.

有效位數規範:小數位數。Precision specifier: Number of decimal digits.

預設的有效位數規範:由 NumberFormatInfo.CurrencyDecimalDigits 定義。Default precision specifier: Defined by NumberFormatInfo.CurrencyDecimalDigits.

詳細資訊:貨幣 ("C") 格式規範More information: The Currency ("C") Format Specifier.
123.456 ("C",en-us)-> \$123.46123.456 ("C", en-US) -> \$123.46

123.456 ("C", fr-FR) -> 123,46 €123.456 ("C", fr-FR) -> 123,46 €

123.456 ("C", ja-JP) -> ¥123123.456 ("C", ja-JP) -> ¥123

-123.456 ("C3",en-us)-> (\$123.456)-123.456 ("C3", en-US) -> (\$123.456)

-123.456 ("C3", fr-FR) -> -123,456 €-123.456 ("C3", fr-FR) -> -123,456 €

-123.456 ("C3", ja-JP) -> -¥123.456-123.456 ("C3", ja-JP) -> -¥123.456
"D" 或 "d""D" or "d" DecimalDecimal 結果:帶選擇性負號的整數位數。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.

詳細資訊:十進位 ("D") 格式規範More information: The Decimal("D") Format Specifier.
1234 ("D") -> 12341234 ("D") -> 1234

-1234 ("D6") -> -001234-1234 ("D6") -> -001234
"E" 或 "e""E" or "e" 指數 (科學記號)Exponential (scientific) 結果:指數標記法。Result: Exponential notation.

支援下列項目:所有數值類型。Supported by: All numeric types.

有效位數規範:小數位數。Precision specifier: Number of decimal digits.

預設的有效位數規範:6.Default precision specifier: 6.

詳細資訊:指數 ("E") 格式規範More information: The Exponential ("E") Format Specifier.
1052.0329112756 ("E", en-US) -> 1.052033E+0031052.0329112756 ("E", en-US) -> 1.052033E+003

1052.0329112756 ("e", fr-FR) -> 1,052033e+0031052.0329112756 ("e", fr-FR) -> 1,052033e+003

-1052.0329112756 ("e2", en-US) -> -1.05e+003-1052.0329112756 ("e2", en-US) -> -1.05e+003

-1052.0329112756 ("E2", fr-FR) -> -1,05E+003-1052.0329112756 ("E2", fr-FR) -> -1,05E+003
"F" 或 "f""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.

預設的有效位數規範:由 NumberFormatInfo.NumberDecimalDigits 定義。Default precision specifier: Defined by NumberFormatInfo.NumberDecimalDigits.

詳細資訊:固定點 ("F") 格式規範More information: The Fixed-Point ("F") Format Specifier.
1234.567 ("F", en-US) -> 1234.571234.567 ("F", en-US) -> 1234.57

1234.567 ("F", de-DE) -> 1234,571234.567 ("F", de-DE) -> 1234,57

1234 ("F1", en-US) -> 1234.01234 ("F1", en-US) -> 1234.0

1234 ("F1", de-DE) -> 1234,01234 ("F1", de-DE) -> 1234,0

-1234.56 ("F4", en-US) -> -1234.5600-1234.56 ("F4", en-US) -> -1234.5600

-1234.56 ("F4", de-DE) -> -1234,5600-1234.56 ("F4", de-DE) -> -1234,5600
"G" 或 "g""G" or "g" 一般General 結果:固定點和科學記號標記法兩者中最精簡的一個。Result: The more 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.

詳細資訊:一般 ("G") 格式規範More information: The General ("G") Format Specifier.
-123.456 ("G", en-US) -> -123.456-123.456 ("G", en-US) -> -123.456

-123.456 ("G", sv-SE) -> -123,456-123.456 ("G", sv-SE) -> -123,456

123.4546 ("G4", en-US) -> 123.5123.4546 ("G4", en-US) -> 123.5

123.4546 ("G4", sv-SE) -> 123,5123.4546 ("G4", sv-SE) -> 123,5

-1.234567890e-25 ("G", en-US) -> -1.23456789E-25-1.234567890e-25 ("G", en-US) -> -1.23456789E-25

-1.234567890e-25 ("G", sv-SE) -> -1,23456789E-25-1.234567890e-25 ("G", sv-SE) -> -1,23456789E-25
"N" 或 "n""N" or "n" numberNumber 結果:帶選擇性負號的整數和小數位數、群組分隔符號,以及小數分隔符號。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.

預設的有效位數規範:由 NumberFormatInfo.NumberDecimalDigits 定義。Default precision specifier: Defined by NumberFormatInfo.NumberDecimalDigits.

詳細資訊:數值 ("N") 格式規範More information: The Numeric ("N") Format Specifier.
1234.567 ("N", en-US) -> 1,234.571234.567 ("N", en-US) -> 1,234.57

1234.567 ("N", ru-RU) -> 1 234,571234.567 ("N", ru-RU) -> 1 234,57

1234 ("N1", en-US) -> 1,234.01234 ("N1", en-US) -> 1,234.0

1234 ("N1", ru-RU) -> 1 234,01234 ("N1", ru-RU) -> 1 234,0

-1234.56 ("N3", en-US) -> -1,234.560-1234.56 ("N3", en-US) -> -1,234.560

-1234.56 ("N3", ru-RU) -> -1 234,560-1234.56 ("N3", ru-RU) -> -1 234,560
"P" 或 "p""P" or "p" 百分比Percent 結果:乘以 100 並加上百分比符號來顯示的數字。Result: Number multiplied by 100 and displayed with a percent symbol.

支援下列項目:所有數值類型。Supported by: All numeric types.

有效位數規範:想要的小數位數。Precision specifier: Desired number of decimal places.

預設的有效位數規範:由 NumberFormatInfo.PercentDecimalDigits 定義。Default precision specifier: Defined by NumberFormatInfo.PercentDecimalDigits.

詳細資訊:百分比 ("P") 格式規範More information: The Percent ("P") Format Specifier.
1 ("P", en-US) -> 100.00 %1 ("P", en-US) -> 100.00 %

1 ("P", fr-FR) -> 100,00 %1 ("P", fr-FR) -> 100,00 %

-0.39678 ("P1", en-US) -> -39.7 %-0.39678 ("P1", en-US) -> -39.7 %

-0.39678 ("P1", fr-FR) -> -39,7 %-0.39678 ("P1", fr-FR) -> -39,7 %
"R" 或 "r""R" or "r" 來回Round-trip 結果:可以來回轉換為相同數字的字串。Result: A string that can round-trip to an identical number.

支援的類型:SingleDoubleBigIntegerSupported by: Single, Double, and BigInteger.

注意:建議僅用於 BigInteger 類型。Note: Recommended for the BigInteger type only. 針對 Double 類型,使用 "G17";針對 Single 類型,使用 "G9"。For Double types, use "G17"; for Single types, use "G9".
有效位數規範:忽略。Precision specifier: Ignored.

詳細資訊:來回 ("R") 格式規範More information: The Round-trip ("R") Format Specifier.
123456789.12345678 ("R") -> 123456789.12345678123456789.12345678 ("R") -> 123456789.12345678

-1234567890.12345678 ("R") -> -1234567890.1234567-1234567890.12345678 ("R") -> -1234567890.1234567
"X" 或 "x""X" or "x" 十六進位Hexadecimal 結果:十六進位字串。Result: A hexadecimal string.

支援下列項目:僅限整數類型。Supported by: Integral types only.

有效位數規範:結果字串中的位數。Precision specifier: Number of digits in the result string.

詳細資訊:十六進位 ("X") 格式規範More information: The HexaDecimal ("X") Format Specifier.
255 ("X") -> FF255 ("X") -> FF

-1 ("x") -> ff-1 ("x") -> ff

255 ("x4") -> 00ff255 ("x4") -> 00ff

-1 ("X4") -> 00FF-1 ("X4") -> 00FF
任何其他單一字元Any other single character 未知的規範Unknown specifier 結果:在執行階段擲回 FormatExceptionResult: Throws a FormatException at run time.

使用標準數值格式字串Using Standard Numeric Format Strings

注意

本文中的 C# 範例會在 Try.NET 內嵌程式碼執行器和測試區執行。The C# examples in this article run in the Try.NET inline code runner and playground. 選取 [執行] 按鈕以在互動式視窗中執行範例。Select the Run button to run an example in an interactive window. 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。Once you execute the code, you can modify it and run the modified code by selecting Run again. 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

使用標準數值格式字串來定義數值的格式有兩種方式:A standard numeric format string can be used to define the formatting of a numeric value in one of two ways:

  • 您可以將它傳遞至具有 ToString 參數之 format 方法的多載。It can be passed to an overload of the ToString method that has a format parameter. 下列範例會以目前的文化特定 (在此範例中是 en-US 文化特性) 來將數值格式化為貨幣字串。The following example formats a numeric value as a currency string in the current culture (in this case, the en-US culture).

    Decimal value = static_cast<Decimal>(123.456);
    Console::WriteLine(value.ToString("C2"));
    // Displays $123.46
    
    decimal value = 123.456m;
    Console.WriteLine(value.ToString("C2"));
    // Displays $123.46
    
    Dim value As Decimal = 123.456d
    Console.WriteLine(value.ToString("C2"))         
    ' Displays $123.46
    
  • 您可以在搭配 String.FormatConsole.WriteLineStringBuilder.AppendFormat 等方法一起使用的格式項目中,提供它作為 formatString 引數。It can be supplied as the formatString argument 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.

    Decimal value = static_cast<Decimal>(123.456);
    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."
    
    Dim value As Decimal = 123.456d
    Console.WriteLine("Your account balance is {0:C2}.", value)
    ' Displays "Your account balance is $123.46."
    

    您可以選擇性地提供 alignment 引數,來指定數值欄位的寬度,以及其值為靠右或靠左對齊。Optionally, you can supply an alignment argument to specify the width of the numeric field and whether its value is right- or left-aligned. 下列範例在 28 個字元的欄位中將貨幣值靠左對齊,並在 14 個字元的欄位中將貨幣值靠右對齊。The following example left-aligns a currency value in a 28-character field, and it right-aligns a currency value in a 14-character field.

    array<Decimal>^ amounts = { static_cast<Decimal>(16305.32), 
                                static_cast<Decimal>(18794.16) };
    Console::WriteLine("   Beginning Balance           Ending Balance");
    Console::WriteLine("   {0,-28:C2}{1,14:C2}", amounts[0], amounts[1]);
    // Displays:
    //        Beginning Balance           Ending Balance
    //        $16,305.32                      $18,794.16      
    
    decimal[] amounts = { 16305.32m, 18794.16m };
    Console.WriteLine("   Beginning Balance           Ending Balance");
    Console.WriteLine("   {0,-28:C2}{1,14:C2}", amounts[0], amounts[1]);
    // Displays:
    //        Beginning Balance           Ending Balance
    //        $16,305.32                      $18,794.16      
    
    Dim amounts() As Decimal = { 16305.32d, 18794.16d }
    Console.WriteLine("   Beginning Balance           Ending Balance")
    Console.WriteLine("   {0,-28:C2}{1,14:C2}", amounts(0), amounts(1))
    ' Displays:
    '        Beginning Balance           Ending Balance
    '        $16,305.32                      $18,794.16      
    
  • 它可以提供作為字串內插補點的插補運算式項目中的 formatString 引數。It can be supplied as the formatString argument in an interpolated expression item of an interpolated string. 如需詳細資訊,請參閱 C# 參考中的字串內插補點主題,或 Visual Basic 參考中的字串內插補點主題。For more information, see the String interpolation topic in the C# reference or the Interpolated strings topic in the Visual Basic reference.

下列各節提供每個標準數值格式字串的詳細資訊。The following sections provide detailed information about each of the standard numeric format strings.

貨幣 ("C") 格式規範The Currency ("C") Format Specifier

"C" (表示貨幣) 格式規範會將數字轉換為表示貨幣金額的字串。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. 如果省略精確度規範,則預設有效位數會由 NumberFormatInfo.CurrencyDecimalDigits 屬性定義。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. 如果指定的小數位數右邊的值為 5 或更大值,則結果字串中的最後一位數會遠離零四捨五入。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.

結果字串會受到目前 NumberFormatInfo 物件的格式設定資訊所影響。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出 NumberFormatInfo 屬性,這些屬性控制傳回之字串的格式設定。The following table lists the NumberFormatInfo properties that control the formatting of the returned string.

NumberFormatInfo 屬性NumberFormatInfo property 描述Description
CurrencyPositivePattern 定義正值的貨幣符號位置。Defines the placement of the currency symbol for positive values.
CurrencyNegativePattern 定義負值的貨幣符號位置,並指定負號是以括號還是 NegativeSign 屬性來表示。Defines the placement of the currency symbol for negative values, and specifies whether the negative sign is represented by parentheses or the NegativeSign property.
NegativeSign 定義在 CurrencyNegativePattern 表示不使用括號時所使用的負號。Defines the negative sign used if CurrencyNegativePattern indicates that parentheses are not used.
CurrencySymbol 定義貨幣符號。Defines the currency symbol.
CurrencyDecimalDigits 定義貨幣值中的預設小數位數。Defines the default number of decimal digits in a currency value. 您可以使用有效位數規範來覆寫這個值。This value can be overridden by using the precision specifier.
CurrencyDecimalSeparator 定義分隔整數與小數位數的字串。Defines the string that separates integral and decimal digits.
CurrencyGroupSeparator 定義分隔整數群組的字串。Defines the string that separates groups of integral numbers.
CurrencyGroupSizes 定義整數部分的每個群組中出現的整數位數。Defines the number of integer digits that appear in a group.

下列範例會使用貨幣Double格式規範來格式化值:The following example formats a Double value with the currency format specifier:

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
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
//       12.345,679 kr
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

回到表格Back to table

十進位 ("D") 格式規範The Decimal ("D") Format Specifier

"D" (表示十進位) 格式規範會將數字轉換為十進位數 (0-9) 的字串,如果數字為負數,則在前面加上負號。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. 只有整數類資料類型 (Integral Type) 才支援這個格式。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.

結果字串會受到目前 NumberFormatInfo 物件的格式設定資訊所影響。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 屬性NumberFormatInfo property 描述Description
NegativeSign 定義表示數字為負數的字串。Defines the string that indicates that a number is negative.

下列範例會使用十進位格式規範來格式化 Int32 值。The following example formats an Int32 value with the decimal format specifier.

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
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
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

回到表格Back to table

指數 ("E") 格式規範The Exponential ("E") Format Specifier

指數 ("E") 格式規範會將數字轉換為 "-d.ddd…E+ddd" 或 "-d.ddd…e+ddd" 形式的字串,其中 "d" 表示數字 (0-9)。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.

格式規範的大小寫表示要在指數之前加上 "E" 還是 "e"。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.

結果字串會受到目前 NumberFormatInfo 物件的格式設定資訊所影響。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出 NumberFormatInfo 屬性,這些屬性控制傳回之字串的格式設定。The following table lists the NumberFormatInfo properties that control the formatting of the returned string.

NumberFormatInfo 屬性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.

下列範例會使用指數Double格式規範來格式化值:The following example formats a Double value with the exponential format specifier:

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
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
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

回到表格Back to table

固定點 ("F") 格式規範The Fixed-Point ("F") Format Specifier

固定點 ("F") 格式規範,會將數字轉換為 "-ddd.ddd…" 形式的字串,其中的每個 "d" 代表一個數字 (0-9)。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. 如果省略精確度規範,則會由目前 NumberFormatInfo.NumberDecimalDigits 屬性提供數值有效位數。If the precision specifier is omitted, the current NumberFormatInfo.NumberDecimalDigits property supplies the numeric precision.

結果字串會受到目前 NumberFormatInfo 物件的格式設定資訊所影響。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出 NumberFormatInfo 物件的屬性,這些屬性控制結果字串的格式設定。The following table lists the properties of the NumberFormatInfo object that control the formatting of the result string.

NumberFormatInfo 屬性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.

下列範例會使用固定點Double格式規範Int32來格式化和值:The following example formats a Double and an Int32 value with the fixed-point format specifier:

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                        
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                        
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                        

回到表格Back to table

一般 ("G") 格式規範The General ("G") Format Specifier

一般 ("G") 格式規範會將數字轉換為固定點和科學標記法兩者中較精簡的一個,視數字的類型以及精確度規範是否存在而定。The general ("G") format specifier converts a number to the more 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.

數字類型Numeric type 預設有效位數Default precision
ByteSByteByte or SByte 3 位數3 digits
Int16UInt16Int16 or UInt16 5 位數5 digits
Int32UInt32Int32 or UInt32 10 位數10 digits
Int64 19 位數19 digits
UInt64 20 位數20 digits
BigInteger 無限制 (如同 "R")Unlimited (same as "R")
Single 7 位數7 digits
Double 15 位數15 digits
Decimal 29 位數29 digits

如果以科學標記法來表示數字所產生的指數大於 -5 而且小於精確度規範,則會使用固定點標記法,否則使用科學標記法。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.

不過,如果數字是 Decimal,而且省略精確度規範,則一律會使用固定點標記法,並且保留尾端的零。However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved.

使用科學標記法時,結果中的指數前面會加上 "E" (如果格式規範為 "G") 或 "e" (如果格式規範為 "g")。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.

請注意,搭配 Double 值使用時,"G17" 格式規範會確保原始的 Double 值可成功地反覆存取。Note that, when used with a Double value, the "G17" format specifier ensures that the original Double value successfully round-trips. 這是因為 Double 是符合 IEEE 754-2008 規範的雙精確度 (binary64) 浮點數,可提供最多 17 個有效位數的精確度。This is because Double is an IEEE 754-2008-compliant double-precision (binary64) floating point number that gives up to 17 significant digits of precision. 建議您使用它,而不是 "R" 格式規範,因為在某些情況下,"R" 無法成功地反覆存取雙精確度浮點值。We recommend its use instead of the "R" format specifier, since in some cases "R" fails to successfully round-trip double-precision floating point values. 下列範例將說明一個這類案例。The following example illustrates one such case.

double original = 0.84551240822557006;
var rSpecifier = original.ToString("R");
var g17Specifier = original.ToString("G17");

var rValue = Double.Parse(rSpecifier);
var g17Value = Double.Parse(g17Specifier);

Console.WriteLine($"{original:G17} = {rSpecifier} (R): {original.Equals(rValue)}");
Console.WriteLine($"{original:G17} = {g17Specifier} (G17): {original.Equals(g17Value)}");
// The example displays the following output:
//     0.84551240822557006 = 0.84551240822557: False
//     0.84551240822557006 = 0.84551240822557006: True
Module Example
   Public Sub Main()
      Dim original As Double = 0.84551240822557006
      Dim rSpecifier = original.ToString("R")
      Dim g17Specifier = original.ToString("G17")
      
      Dim rValue = Double.Parse(rSpecifier)
      Dim g17Value = Double.Parse(g17Specifier)
      
      Console.WriteLine($"{original:G17} = {rSpecifier} (R): {original.Equals(rValue)}")
      Console.WriteLine($"{original:G17} = {g17Specifier} (G17): {original.Equals(g17Value)}")
   End Sub
End Module
' The example displays the following output:
'     0.84551240822557006 = 0.84551240822557 (R): False
'     0.84551240822557006 = 0.84551240822557006 (G17): True
  

搭配 Single 值使用時,"G9" 格式規範會確保原始的 Single 值可成功地反覆存取。When used with a Single value, the "G9" format specifier ensures that the original Single value successfully round-trips. 這是因為 Single 是符合 IEEE 754-2008 規範的單精確度 (binary32) 浮點數,可提供最多九個有效位數的精確度。This is because Single is an IEEE 754-2008-compliant single-precision (binary32) floating point number that gives up to nine significant digits of precision. 基於效能考量,我們建議使用它,而不要使用 "R" 格式規範For performance reasons, we recommend its use instead of the "R" format specifier.

結果字串會受到目前 NumberFormatInfo 物件的格式設定資訊所影響。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出可控制結果字串之格式設定的 NumberFormatInfo 屬性。The following table lists the NumberFormatInfo properties that control the formatting of the result string.

NumberFormatInfo 屬性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 assorted floating-point values with the general format specifier:

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    
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    
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    

回到表格Back to table

數值 ("N") 格式規範The Numeric ("N") Format Specifier

數字 ("N") 格式規範會將數字轉換為 "-d,ddd,ddd.ddd…" 形式的字串,其中 "-" 表示負數符號 (如有需要)、"d" 表示數字 (0-9)、"," 表示群組分隔符號,而 "." 表示小數點符號。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. 如果省略精確度規範,則小數位數會由目前的 NumberFormatInfo.NumberDecimalDigits 屬性定義。If the precision specifier is omitted, the number of decimal places is defined by the current NumberFormatInfo.NumberDecimalDigits property.

結果字串會受到目前 NumberFormatInfo 物件的格式設定資訊所影響。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出可控制結果字串之格式設定的 NumberFormatInfo 屬性。The following table lists the NumberFormatInfo properties that control the formatting of the result string.

NumberFormatInfo 屬性NumberFormatInfo property 描述Description
NegativeSign 定義表示數字為負數的字串。Defines the string that indicates that a number is negative.
NumberNegativePattern 定義負值的格式,並指定負號是以括號還是 NegativeSign 屬性來表示。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:

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 
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 
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 

回到表格Back to table

百分比 ("P") 格式規範The Percent ("P") Format Specifier

百分比 ("P") 格式規範會將數字乘以 100,然後轉換為表示百分比的字串。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. 如果省略精確度規範,則會使用目前 PercentDecimalDigits 屬性所提供的預設數值有效位數。If the precision specifier is omitted, the default numeric precision supplied by the current PercentDecimalDigits property is used.

下表列出 NumberFormatInfo 屬性,這些屬性控制傳回之字串的格式設定。The following table lists the NumberFormatInfo properties that control the formatting of the returned string.

NumberFormatInfo 屬性NumberFormatInfo property 描述Description
PercentPositivePattern 定義正值的百分比符號位置。Defines the placement of the percent symbol for positive values.
PercentNegativePattern 定義負值的百分比符號位置和負號位置。Defines the placement of the percent symbol and the negative symbol for negative values.
NegativeSign 定義表示數字為負數的字串。Defines the string that indicates that a number is negative.
PercentSymbol 定義百分比符號。Defines the percent symbol.
PercentDecimalDigits 定義百分比值中的預設小數位數。Defines the default number of decimal digits in a percentage value. 您可以使用有效位數規範來覆寫這個值。This value can be overridden by using the precision specifier.
PercentDecimalSeparator 定義分隔整數與小數位數的字串。Defines the string that separates integral and decimal digits.
PercentGroupSeparator 定義分隔整數群組的字串。Defines the string that separates groups of integral numbers.
PercentGroupSizes 定義整數部分的每個群組中出現的整數位數。Defines the number of integer digits that appear in a group.

下列範例會使用百分比格式規範來格式化浮點值:The following example formats floating-point values with the percent format specifier:

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 %
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 %
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 %

回到表格Back to table

來回 ("R") 格式規範The Round-trip ("R") Format Specifier

反覆存取 ("R") 格式規範會嘗試確保可將轉換為字串的數值剖析回相同的數值。The round-trip ("R") format specifier attempts to ensure that a numeric value that is converted to a string is parsed back into the same numeric value. 只有 SingleDoubleBigInteger 類型才支援這個格式。This format is supported only for the Single, Double, and BigInteger types.

針對 Double 值,"R" 格式規範在某些情況下無法成功地反覆存取原始值。For Double values, the "R" format specifier in some cases fails to successfully round-trip the original value. 針對 DoubleSingle 值,它也提供相當差的效能。For both Double and Single values, it also offers relatively poor performance. 我們建議您針對 Double 值改用 "G17" 格式規範以及 "G9" 格式規範,以便成功地反覆存取 Single 值。Instead, we recommend that you use the "G17" format specifier for Double values and the "G9" format specifier to successfully round-trip Single values.

使用這個規範來格式化 BigInteger 值時,這個值的字串表示會包含 BigInteger 值中的所有有效位數。When a BigInteger value is formatted using this specifier, its string representation contains all the significant digits in the BigInteger value.

雖然您可以包含精確度規範,但該規範會被忽略。Although you can include a precision specifier, it is ignored. 使用來回規範時,這個規範優先於精確度規範。Round trips are given precedence over precision when using this specifier. 結果字串會受到目前 NumberFormatInfo 物件的格式設定資訊所影響。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出可控制結果字串之格式設定的 NumberFormatInfo 屬性。The following table lists the NumberFormatInfo properties that control the formatting of the result string.

NumberFormatInfo 屬性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.

下列範例會使用反覆存取格式規範來將 BigInteger 值格式化。The following example formats a BigInteger value with the round-trip format specifier.

#using <System.Numerics.dll>

using namespace System;
using namespace System::Numerics;

void main()
{ 
   BigInteger value = BigInteger::Pow(Int64::MaxValue, 2);
   Console::WriteLine(value.ToString("R"));
}
// The example displays the following output:
//      85070591730234615847396907784232501249  


using System;
using System.Numerics;

public class Example
{
   public static void Main()
   { 
      var value = BigInteger.Pow(Int64.MaxValue, 2);
      Console.WriteLine(value.ToString("R"));
   }
}                                                                                        
// The example displays the following output:
//      85070591730234615847396907784232501249  
Imports System.Numerics

Module Example
   Public Sub Main()
      Dim value = BigInteger.Pow(Int64.MaxValue, 2)
      Console.WriteLine(value.ToString("R"))
   End Sub
End Module
' The example displays the following output:
'      85070591730234615847396907784232501249  

重要

在某些情況下,使用 "R" 標準數值格式字串格式化的 Double 值,如果使用 /platform:x64/platform:anycpu 參數編譯並在 64 位元系統上執行,則不會成功地反覆存取。In some cases, Double values formatted with the "R" standard numeric format string do not successfully round-trip if compiled using the /platform:x64 or /platform:anycpu switches and run on 64-bit systems. 如需詳細資訊,請參閱下一段內容。See the following paragraph for more information.

若要解決以 "R" 標準數值格式字串格式化的 Double 值,在使用 /platform:x64/platform:anycpu 參數編譯並於 64 位元系統上執行時,不會成功地反覆存取的問題,您可以使用 "G17" 標準數值格式字串格式化 Double 值。To work around the problem of Double values formatted with the "R" standard numeric format string not successfully round-tripping if compiled using the /platform:x64 or /platform:anycpu switches and run on 64-bit systems., you can format Double values by using the "G17" standard numeric format string. 下列範例會使用 "R" 格式字串,其Double值不會成功地往返,而且也會使用 "G17" 格式字串來成功地反復存取原始值:The following example uses the "R" format string with a Double value that does not round-trip successfully, and also uses the "G17" format string to successfully round-trip the original value:

Console.WriteLine("Attempting to round-trip a Double with 'R':");
double initialValue = 0.6822871999174;
string valueString = initialValue.ToString("R",
                                           CultureInfo.InvariantCulture);
double roundTripped = double.Parse(valueString,
                                   CultureInfo.InvariantCulture);
Console.WriteLine("{0:R} = {1:R}: {2}\n",
                  initialValue, roundTripped, initialValue.Equals(roundTripped));

Console.WriteLine("Attempting to round-trip a Double with 'G17':");
string valueString17 = initialValue.ToString("G17",
                                             CultureInfo.InvariantCulture);
double roundTripped17 = double.Parse(valueString17,
                                     CultureInfo.InvariantCulture);
Console.WriteLine("{0:R} = {1:R}: {2}\n",
                  initialValue, roundTripped17, initialValue.Equals(roundTripped17));
// If compiled to an application that targets anycpu or x64 and run on an x64 system,
// the example displays the following output:
//       Attempting to round-trip a Double with 'R':
//       0.6822871999174 = 0.68228719991740006: False
//
//       Attempting to round-trip a Double with 'G17':
//       0.6822871999174 = 0.6822871999174: True
Imports System.Globalization

Module Example
   Public Sub Main()
      Console.WriteLine("Attempting to round-trip a Double with 'R':")
      Dim initialValue As Double = 0.6822871999174
      Dim valueString As String = initialValue.ToString("R",
                                               CultureInfo.InvariantCulture)
      Dim roundTripped As Double = Double.Parse(valueString,
                                                CultureInfo.InvariantCulture)
      Console.WriteLine("{0:R} = {1:R}: {2}",
                        initialValue, roundTripped, initialValue.Equals(roundTripped))
      Console.WriteLine()
      
      Console.WriteLine("Attempting to round-trip a Double with 'G17':")
      Dim valueString17 As String = initialValue.ToString("G17",
                                                 CultureInfo.InvariantCulture)
      Dim roundTripped17 As Double = double.Parse(valueString17,
                                            CultureInfo.InvariantCulture)
      Console.WriteLine("{0:R} = {1:R}: {2}",
                        initialValue, roundTripped17, initialValue.Equals(roundTripped17))
   End Sub
End Module
' If compiled to an application that targets anycpu or x64 and run on an x64 system,
' the example displays the following output:
'       Attempting to round-trip a Double with 'R':
'       0.6822871999174 = 0.68228719991740006: False
'
'       Attempting to round-trip a Double with 'G17':
'       0.6822871999174 = 0.6822871999174: True

回到表格Back to table

十六進位 ("X") 格式規範The Hexadecimal ("X") Format Specifier

十六進位 ("X") 格式規範會將數字轉換為十六進位數字的字串。The hexadecimal ("X") format specifier converts a number to a string of hexadecimal digits. 格式規範的大小寫表示對於大於 9 的十六進位數字,要使用大寫還是小寫字元。The case of the format specifier indicates whether to use uppercase or lowercase characters for hexadecimal digits that are greater than 9. 例如,使用 "X" 會產生 "ABCDEF",使用 "x" 則會產生 "abcdef"。For example, use "X" to produce "ABCDEF", and "x" to produce "abcdef". 只有整數類資料類型 (Integral Type) 才支援這個格式。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.

結果字串不受目前 NumberFormatInfo 物件的格式設定資訊所影響。The result string is not affected by the formatting information of the current NumberFormatInfo object.

下列範例會使用十六進位格式規範格式化 Int32 值。The following example formats Int32 values with the hexadecimal format specifier.

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
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
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

回到表格Back to table

注意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. 這些設定是用來初始化與目前執行緒文化特性相關的 NumberFormatInfo 物件,該物件會提供用來管理格式的值。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.

此外,如果使用 CultureInfo.CultureInfo(String) 建構函式來將新的 CultureInfo 物件具現化,而此物件代表的文化特性與目前系統文化特性相同,則 [控制台] 中的 [地區及語言選項] 項目所建立的任何自訂都會套用至新的 CultureInfo 物件。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. 您可以使用 CultureInfo.CultureInfo(String, Boolean) 建構函式來建立不反映系統自訂的 CultureInfo 物件。You can use the CultureInfo.CultureInfo(String, Boolean) constructor to create a CultureInfo object that does not reflect a system's customizations.

NumberFormatInfo 屬性NumberFormatInfo Properties

格式會受到目前 NumberFormatInfo 物件屬性的影響,而此物件是由目前執行緒文化特性隱含提供或由叫用格式之方法的 IFormatProvider 參數明確提供。Formatting 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. 為該參數指定 NumberFormatInfoCultureInfo 物件。Specify a NumberFormatInfo or CultureInfo object for that parameter.

注意

如需有關自訂格式化數值所使用之模式或字串的詳細資訊,請參閱 NumberFormatInfo 類別主題。For information about customizing the patterns or strings used in formatting numeric values, see the NumberFormatInfo class topic.

整數類資料類型和浮點數值類型Integral and Floating-Point Numeric Types

標準數值格式規範的某些描述會參考整數類資料類型或浮點數值類型。Some descriptions of standard numeric format specifiers refer to integral or floating-point numeric types. 整數數字類型為 ByteSByteInt16Int32Int64UInt16UInt32UInt64BigIntegerThe integral numeric types are Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, and BigInteger. 浮點數值類型有 DecimalSingleDoubleThe floating-point numeric types are Decimal, Single, and Double.

無限浮點數和 NaNFloating-Point Infinities and NaN

不論格式字串為何,如果 SingleDouble 浮點類型的值為正無限大、負無限大或不是數字 (NaN),則格式化後的字串會分別是 PositiveInfinitySymbolNegativeInfinitySymbolNaNSymbol 屬性的值 (這些屬性由目前適用的 NumberFormatInfo 物件所指定)。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 that is specified by the currently applicable NumberFormatInfo object.

範例Example

注意

本文中的某些 C# 範例會在 Try.NET 內嵌程式碼執行器和測試區執行。Some of the C# examples in this article run in the Try.NET inline code runner and playground. 選取 [執行] 按鈕以在互動式視窗中執行範例。Select the Run button to run an example in an interactive window. 執行程式碼之後,您便可以修改它,並再選取一次 [執行] 來執行修改過的程式碼。Once you execute the code, you can modify it and run the modified code by selecting Run again. 修改過的程式碼會在互動式視窗中執行,或是如果編譯失敗的話,互動式視窗會顯示所有 C# 編譯器錯誤訊息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

下列範例會使用 en-US 文化特性和所有標準數值格式規範來格式化整數和浮點數值。The following example formats an integral and a floating-point numeric value using the en-US culture and all the standard numeric format specifiers. 這個範例使用兩個特定的數字類型 (DoubleInt32),但用於其他任何數字基底類型 (ByteSByteInt16Int32Int64UInt16UInt32UInt64BigIntegerDecimalSingle) 也會產生類似的結果。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).

// 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();
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

另請參閱See also