自訂數值格式字串Custom numeric format strings

您可以建立由一個或多個自訂數值規範所組成的自訂數值格式字串,以定義如何格式化數值資料。You can create a custom numeric format string, which consists of one or more custom numeric specifiers, to define how to format numeric data. 自訂數值格式字串為任何非 標準數值格式字串的格式字串。A custom numeric format string is any format string that is not a standard numeric format string.

所有數字類型的 ToString 方法的一些多載可支援自訂數值格式字串。Custom numeric format strings are supported by some overloads of the ToString method of all numeric types. 例如,您可以提供數值格式字串給 ToString(String) 類型的 ToString(String, IFormatProvider)Int32 方法。For example, you can supply a numeric format string to the ToString(String) and ToString(String, IFormatProvider) methods of the Int32 type. .NET 的複合格式功能也支援自訂數值格式字串,此功能會由 ConsoleStreamWriter 類別的一些 WriteWriteLine 方法,以及 String.Format 方法和 StringBuilder.AppendFormat 方法所使用。Custom numeric format strings are also supported by the .NET 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. 字串內插補點功能也支援自訂數值格式字串。String interpolation feature also supports custom numeric format strings.

提示

您可以下載格式化公用程式,這個 .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 custom numeric format specifiers and displays sample output produced by each format specifier. 如需使用自訂數值格式字串的詳細資訊,請參閱 注意 一節,如需其用法的完整解說,請參閱 範例 一節。See the Notes section for additional information about using custom numeric format strings, and the Example section for a comprehensive illustration of their use.

格式規範Format specifier 名稱Name 說明Description 範例Examples
"0""0" 零值預留位置Zero placeholder 以對應的數字 (如果有的話) 取代零,否則結果字串中會出現零。Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

詳細資訊:"0" 自訂規範More information: The "0" Custom Specifier.
1234.5678 ("00000") -> 012351234.5678 ("00000") -> 01235

0.45678 ("0.00", en-US) -> 0.460.45678 ("0.00", en-US) -> 0.46

0.45678 ("0.00", fr-FR) -> 0,460.45678 ("0.00", fr-FR) -> 0,46
"#""#" 數字預留位置Digit placeholder 將 "#" 符號取代為對應的數字 (如果有的話),否則結果字串中不會出現任何數字。Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.

請注意,如果輸入字串中對應的數字是不重要的 0,結果字串中就不會顯示任何數字。Note that no digit appears in the result string if the corresponding digit in the input string is a non-significant 0. 例如,0003 ("####") -> 3。For example, 0003 ("####") -> 3.

詳細資訊:"#" 自訂規範More information: The "#" Custom Specifier.
1234.5678 ("#####") -> 12351234.5678 ("#####") -> 1235

0.45678 ("#.##", en-US) -> .460.45678 ("#.##", en-US) -> .46

0.45678 ("#.##", fr-FR) -> ,460.45678 ("#.##", fr-FR) -> ,46
".""." 小數點Decimal point 決定結果字串中小數點的位置。Determines the location of the decimal separator in the result string.

詳細資訊:"."自訂規範More information: The "." Custom Specifier.
0.45678 ("0.00", en-US) -> 0.460.45678 ("0.00", en-US) -> 0.46

0.45678 ("0.00", fr-FR) -> 0,460.45678 ("0.00", fr-FR) -> 0,46
",""," 群組分隔符號和數值範圍Group separator and number scaling 同時做為群組分隔符號和數值縮放規範。Serves as both a group separator and a number scaling specifier. 如果做為群組分隔符號,則會在每個群組之間插入當地語系化群組分隔符號字元。As a group separator, it inserts a localized group separator character between each group. 做為數值縮放規範時,每指定一個逗號就會將數字除以 1000。As a number scaling specifier, it divides a number by 1000 for each comma specified.

詳細資訊:"," 自訂規範More information: The "," Custom Specifier.
群組分隔符號規範:Group separator specifier:

2147483647 ("##,#", en-US) -> 2,147,483,6472147483647 ("##,#", en-US) -> 2,147,483,647

2147483647 ("##,#", es-ES) -> 2.147.483.6472147483647 ("##,#", es-ES) -> 2.147.483.647

縮放規範:Scaling specifier:

2147483647 ("#,#,,", en-US) -> 2,1472147483647 ("#,#,,", en-US) -> 2,147

2147483647 ("#,#,,", es-ES) -> 2.1472147483647 ("#,#,,", es-ES) -> 2.147
"%""%" 百分比預留位置Percentage placeholder 將數字乘以 100,並在結果字串中插入當地語系化的百分比符號。Multiplies a number by 100 and inserts a localized percentage symbol in the result string.

詳細資訊:"%" 自訂規範More information: The "%" Custom Specifier.
0.3697 ("%#0.00", en-US) -> %36.970.3697 ("%#0.00", en-US) -> %36.97

0.3697 ("%#0.00", el-GR) -> %36,970.3697 ("%#0.00", el-GR) -> %36,97

0.3697 ("##.0 %", en-US) -> 37.0 %0.3697 ("##.0 %", en-US) -> 37.0 %

0.3697 ("##.0 %", el-GR) -> 37,0 %0.3697 ("##.0 %", el-GR) -> 37,0 %
"‰""‰" 千分之一符號預留位置Per mille placeholder 將數字乘以 1000,並在結果字串中插入當地語系化的千分比符號。Multiplies a number by 1000 and inserts a localized per mille symbol in the result string.

詳細資訊:"‰" 自訂規範More information: The "‰" Custom Specifier.
0.03697 ("#0.00‰", en-US) -> 36.97‰0.03697 ("#0.00‰", en-US) -> 36.97‰

0.03697 ("#0.00‰", ru-RU) -> 36,97‰0.03697 ("#0.00‰", ru-RU) -> 36,97‰
"E0""E0"

"E+0""E+0"

"E-0""E-0"

"E0""e0"

"E+0""e+0"

"E-0""e-0"
指數標記法Exponential notation 如果後面至少接著一個 0 (零),則使用指數標記法來格式化結果。If followed by at least one 0 (zero), formats the result using exponential notation. 大小寫 "E" 或 "e" 表示結果字串中指數符號的大小寫。The case of "E" or "e" indicates the case of the exponent symbol in the result string. 接在 "E" 或 "e" 字元後面的零個數決定指數中的最少位數。The number of zeros following the "E" or "e" character determines the minimum number of digits in the exponent. 加號 (+) 表示指數前面一律加上正負號字元。A plus sign (+) indicates that a sign character always precedes the exponent. 減號 (-) 表示只在負指數前面才加上正負號字元。A minus sign (-) indicates that a sign character precedes only negative exponents.

詳細資訊:"E" 和 "e" 自訂規範More information: The "E" and "e" Custom Specifiers.
987654 ("#0.0e0") -> 98.8e4987654 ("#0.0e0") -> 98.8e4

1503.92311 ("0.0##e+00") -> 1.504e+031503.92311 ("0.0##e+00") -> 1.504e+03

1.8901385E-16 ("0.0e+00") -> 1.9e-161.8901385E-16 ("0.0e+00") -> 1.9e-16
"\""\" 逸出字元Escape character 將下一個字元解譯為常值,而不是自訂格式規範。Causes the next character to be interpreted as a literal rather than as a custom format specifier.

詳細資訊:"\" 逸出字元More information: The "\" Escape Character.
987654 ("\###00\#") -> #987654#987654 ("\###00\#") -> #987654#
'string''string'

"字串""string"
常值字串分隔符號Literal string delimiter 表示應該將所括住的字元原封不動地複製到結果字串。Indicates that the enclosed characters should be copied to the result string unchanged.

詳細資訊:字元常值More information: Character literals.
68 ("# 'degrees'") -> 68 degrees68 ("# 'degrees'") -> 68 degrees

68 ("# ' degrees'") -> 68 degrees68 ("#' degrees'") -> 68 degrees
;; 區段分隔符號Section separator 以個別格式字串來定義正數、負數和零值的區段。Defines sections with separate format strings for positive, negative, and zero numbers.

詳細資訊:";" 區段分隔符號More information: The ";" Section Separator.
12.345 ("#0.0#;(#0.0#);-\0-") -> 12.3512.345 ("#0.0#;(#0.0#);-\0-") -> 12.35

0 ("#0.0#;(#0.0#);-\0-") -> -0-0 ("#0.0#;(#0.0#);-\0-") -> -0-

-12.345 ("#0.0#;(#0.0#);-\0-") -> (12.35)-12.345 ("#0.0#;(#0.0#);-\0-") -> (12.35)

12.345 ("#0.0#;(#0.0#)") -> 12.3512.345 ("#0.0#;(#0.0#)") -> 12.35

0 ("#0.0#;(#0.0#)") -> 0.00 ("#0.0#;(#0.0#)") -> 0.0

-12.345 ("#0.0#;(#0.0#)") -> (12.35)-12.345 ("#0.0#;(#0.0#)") -> (12.35)
其他Other 所有其他字元All other characters 字元會原封不動地複製到結果字串。The character is copied to the result string unchanged.

詳細資訊:字元常值More information: Character literals.
68 ("# °") -> 68 °68 ("# °") -> 68 °

下列各節提供每個自訂數值格式規範的詳細資訊。The following sections provide detailed information about each of the custom numeric format specifiers.

注意

本文中的某些 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.

"0" 自訂規範The "0" custom specifier

"0" 自訂格式規範是當做零預留位置符號。The "0" custom format specifier serves as a zero-placeholder symbol. 如果正在格式化的值有數字位於格式字串中出現零的位置上,則該數字會複製到結果字串,否則結果字串中會出現零。If the value that is being formatted has a digit in the position where the zero appears in the format string, that digit is copied to the result string; otherwise, a zero appears in the result string. 小數點前最左邊的零和小數點後最右邊的零位置,決定要一直在輸出字串中出現的位數範圍。The position of the leftmost zero before the decimal point and the rightmost zero after the decimal point determines the range of digits that are always present in the result string.

"00" 規範會造成數值捨入至最接近的小數點前面數值,而其中永遠使用遠離零的捨入方式。The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. 例如,使用 "00" 格式化 34.5 將會得到值 35。For example, formatting 34.5 with "00" would result in the value 35.

下列範例顯示使用包含零預留位置的自訂格式字串來格式化的幾個值。The following example displays several values that are formatted by using custom format strings that include zero placeholders.

double value;

value = 123;
Console::WriteLine(value.ToString("00000"));
Console::WriteLine(String::Format("{0:00000}", value));
// Displays 00123

value = 1.2;
Console::WriteLine(value.ToString("0.00", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                  "{0:0.00}", value));
// Displays 1.20

Console::WriteLine(value.ToString("00.00", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:00.00}", value));
// Displays 01.20

CultureInfo^ daDK = CultureInfo::CreateSpecificCulture("da-DK");
Console::WriteLine(value.ToString("00.00", daDK)); 
Console::WriteLine(String::Format(daDK, "{0:00.00}", value));
// Displays 01,20

value = .56;
Console::WriteLine(value.ToString("0.0", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:0.0}", value));
// Displays 0.6

value = 1234567890;
Console::WriteLine(value.ToString("0,0", CultureInfo::InvariantCulture));	
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:0,0}", value));	
// Displays 1,234,567,890      

CultureInfo^ elGR = CultureInfo::CreateSpecificCulture("el-GR");
Console::WriteLine(value.ToString("0,0", elGR));	
Console::WriteLine(String::Format(elGR, "{0:0,0}", value));	
// Displays 1.234.567.890

value = 1234567890.123456;
Console::WriteLine(value.ToString("0,0.0", CultureInfo::InvariantCulture));	
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:0,0.0}", value));	
// Displays 1,234,567,890.1  

value = 1234.567890;
Console::WriteLine(value.ToString("0,0.00", CultureInfo::InvariantCulture));	
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:0,0.00}", value));	
// Displays 1,234.57 
 double value;
 
 value = 123;
 Console.WriteLine(value.ToString("00000"));
 Console.WriteLine(String.Format("{0:00000}", value));
 // Displays 00123
 
 value = 1.2;
 Console.WriteLine(value.ToString("0.00", CultureInfo.InvariantCulture));
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                   "{0:0.00}", value));
 // Displays 1.20

 Console.WriteLine(value.ToString("00.00", CultureInfo.InvariantCulture));
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                 "{0:00.00}", value));
 // Displays 01.20

 CultureInfo daDK = CultureInfo.CreateSpecificCulture("da-DK");
 Console.WriteLine(value.ToString("00.00", daDK)); 
 Console.WriteLine(String.Format(daDK, "{0:00.00}", value));
 // Displays 01,20
 
 value = .56;
 Console.WriteLine(value.ToString("0.0", CultureInfo.InvariantCulture));
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                 "{0:0.0}", value));
 // Displays 0.6

 value = 1234567890;
 Console.WriteLine(value.ToString("0,0", CultureInfo.InvariantCulture));	
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                 "{0:0,0}", value));	
 // Displays 1,234,567,890      
 
 CultureInfo elGR = CultureInfo.CreateSpecificCulture("el-GR");
 Console.WriteLine(value.ToString("0,0", elGR));	
Console.WriteLine(String.Format(elGR, "{0:0,0}", value));	
 // Displays 1.234.567.890
 
 value = 1234567890.123456;
 Console.WriteLine(value.ToString("0,0.0", CultureInfo.InvariantCulture));	
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                 "{0:0,0.0}", value));	
 // Displays 1,234,567,890.1  
 
 value = 1234.567890;
 Console.WriteLine(value.ToString("0,0.00", CultureInfo.InvariantCulture));	
 Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                 "{0:0,0.00}", value));	
 // Displays 1,234.57 
Dim value As Double

value = 123
Console.WriteLine(value.ToString("00000"))
Console.WriteLine(String.Format("{0:00000}", value))
' Displays 00123

value = 1.2
Console.Writeline(value.ToString("0.00", CultureInfo.InvariantCulture))
Console.Writeline(String.Format(CultureInfo.InvariantCulture, 
                  "{0:0.00}", value))
' Displays 1.20
Console.WriteLine(value.ToString("00.00", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:00.00}", value))
' Displays 01.20
Dim daDK As CultureInfo = CultureInfo.CreateSpecificCulture("da-DK")
Console.WriteLine(value.ToString("00.00", daDK))
Console.WriteLine(String.Format(daDK, "{0:00.00}", value))
' Displays 01,20

value = .56
Console.WriteLine(value.ToString("0.0", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0.0}", value))
' Displays 0.6

value = 1234567890
Console.WriteLine(value.ToString("0,0", CultureInfo.InvariantCulture))	
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0,0}", value))	
' Displays 1,234,567,890      
Dim elGR As CultureInfo = CultureInfo.CreateSpecificCulture("el-GR")
Console.WriteLine(value.ToString("0,0", elGR))
Console.WriteLine(String.Format(elGR, "{0:0,0}", value))	
' Displays 1.234.567.890

value = 1234567890.123456
Console.WriteLine(value.ToString("0,0.0", CultureInfo.InvariantCulture))	
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0,0.0}", value))	
' Displays 1,234,567,890.1  

value = 1234.567890
Console.WriteLine(value.ToString("0,0.00", CultureInfo.InvariantCulture))	
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0,0.00}", value))	
' Displays 1,234.57 

回到表格Back to table

"#" 自訂規範The "#" custom specifier

"#" 自訂格式規範是當做數字預留位置符號。The "#" custom format specifier serves as a digit-placeholder symbol. 如果正在格式化的值有數字位於格式字串中出現 "#" 符號的位置上,則該數字會複製到輸出字串。If the value that is being formatted has a digit in the position where the "#" symbol appears in the format string, that digit is copied to the result string. 否則,沒有東西會存放在結果字串中的那個位置。Otherwise, nothing is stored in that position in the result string.

請注意,這個規範永遠不會顯示不是有效位數的零,即使字串中只有零這個數字也一樣。Note that this specifier never displays a zero that is not a significant digit, even if zero is the only digit in the string. 只有當零在所顯示的數字中是有效位數時,才會顯示零。It will display zero only if it is a significant digit in the number that is being displayed.

"##" 格式字串會造成數值捨入至最接近的小數點前面數值,而其中永遠使用遠離零的捨入方式。The "##" format string causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. 例如,使用 "##" 格式化 34.5 將會得到值 35。For example, formatting 34.5 with "##" would result in the value 35.

下列範例顯示使用包含數字預留位置的自訂格式字串來格式化的幾個值。The following example displays several values that are formatted by using custom format strings that include digit placeholders.

 double value;
 
 value = 1.2;
 Console::WriteLine(value.ToString("#.##", CultureInfo::InvariantCulture));
 Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                 "{0:#.##}", value));
 // Displays 1.2
 
 value = 123;
 Console::WriteLine(value.ToString("#####"));
 Console::WriteLine(String::Format("{0:#####}", value));
 // Displays 123

 value = 123456;
 Console::WriteLine(value.ToString("[##-##-##]"));      
 Console::WriteLine(String::Format("{0:[##-##-##]}", value));      
// Displays [12-34-56]

 value = 1234567890;
 Console::WriteLine(value.ToString("#"));
 Console::WriteLine(String::Format("{0:#}", value));
 // Displays 1234567890
 
 Console::WriteLine(value.ToString("(###) ###-####"));
 Console::WriteLine(String::Format("{0:(###) ###-####}", value));
 // Displays (123) 456-7890
double value;

value = 1.2;
Console.WriteLine(value.ToString("#.##", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#.##}", value));
// Displays 1.2

value = 123;
Console.WriteLine(value.ToString("#####"));
Console.WriteLine(String.Format("{0:#####}", value));
// Displays 123

value = 123456;
Console.WriteLine(value.ToString("[##-##-##]"));      
Console.WriteLine(String.Format("{0:[##-##-##]}", value));      
 // Displays [12-34-56]

value = 1234567890;
Console.WriteLine(value.ToString("#"));
Console.WriteLine(String.Format("{0:#}", value));
// Displays 1234567890

Console.WriteLine(value.ToString("(###) ###-####"));
Console.WriteLine(String.Format("{0:(###) ###-####}", value));
// Displays (123) 456-7890
Dim value As Double

value = 1.2
Console.WriteLine(value.ToString("#.##", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#.##}", value))
' Displays 1.2

value = 123
Console.WriteLine(value.ToString("#####"))
Console.WriteLine(String.Format("{0:#####}", value))
' Displays 123

value = 123456
Console.WriteLine(value.ToString("[##-##-##]"))      
Console.WriteLine(String.Format("{0:[##-##-##]}", value))      
 ' Displays [12-34-56]

value = 1234567890
Console.WriteLine(value.ToString("#"))
Console.WriteLine(String.Format("{0:#}", value))
' Displays 1234567890

Console.WriteLine(value.ToString("(###) ###-####"))
Console.WriteLine(String.Format("{0:(###) ###-####}", value))
' Displays (123) 456-7890

若要傳回結果字串,以空格取代不存在的數字或前置零,請使用 複合格式功能 並指定欄位寬度,如下列範例所示。To return a result string in which absent digits or leading zeroes are replaced by spaces, use the composite formatting feature and specify a field width, as the following example illustrates.

using namespace System;

void main()
{
    Double value = .324;
    Console::WriteLine("The value is: '{0,5:#.###}'", value);
}
// The example displays the following output if the current culture
// is en-US:
//      The value is: ' .324'
using System;

public class Example
{
   public static void Main()
   {
      Double value = .324;
      Console.WriteLine("The value is: '{0,5:#.###}'", value);
   }
}
// The example displays the following output if the current culture
// is en-US:
//      The value is: ' .324'
Module Example
   Public Sub Main()
      Dim value As Double = .324
      Console.WriteLine("The value is: '{0,5:#.###}'", value)
   End Sub
End Module
' The example displays the following output if the current culture
' is en-US:
'      The value is: ' .324'

回到表格Back to table

"." 自訂規範The "." custom specifier

"." 自訂格式規範會將當地語系化的十進位分隔符號插入結果字串中。The "." custom format specifier inserts a localized decimal separator into the result string. 格式字串中第一個點決定所格式化值中的小數分隔符號位置;任何其他點將被忽略。The first period in the format string determines the location of the decimal separator in the formatted value; any additional periods are ignored.

結果字串中當做小數分隔符號的字元不一定是點,而是由控制格式設定的 NumberDecimalSeparator 物件的 NumberFormatInfo 屬性來決定。The character that is used as the decimal separator in the result string is not always a period; it is determined by the NumberDecimalSeparator property of the NumberFormatInfo object that controls formatting.

下列範例使用 "." 格式規範來定義幾個結果字串中小數點的位置。The following example uses the "." format specifier to define the location of the decimal point in several result strings.

 double value;
 
 value = 1.2;
 Console::WriteLine(value.ToString("0.00", CultureInfo::InvariantCulture));
 Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                 "{0:0.00}", value));
 // Displays 1.20

 Console::WriteLine(value.ToString("00.00", CultureInfo::InvariantCulture));
 Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                 "{0:00.00}", value));
 // Displays 01.20

 Console::WriteLine(value.ToString("00.00", 
                   CultureInfo::CreateSpecificCulture("da-DK")));
 Console::WriteLine(String::Format(CultureInfo::CreateSpecificCulture("da-DK"),
                   "{0:00.00}", value));
 // Displays 01,20

 value = .086;
 Console::WriteLine(value.ToString("#0.##%", CultureInfo::InvariantCulture)); 
 Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                 "{0:#0.##%}", value)); 
 // Displays 8.6%
  
 value = 86000;
 Console::WriteLine(value.ToString("0.###E+0", CultureInfo::InvariantCulture));
 Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                   "{0:0.###E+0}", value));
// Displays 8.6E+4
double value;

value = 1.2;
Console.WriteLine(value.ToString("0.00", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0.00}", value));
// Displays 1.20

Console.WriteLine(value.ToString("00.00", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:00.00}", value));
// Displays 01.20

Console.WriteLine(value.ToString("00.00", 
                  CultureInfo.CreateSpecificCulture("da-DK")));
Console.WriteLine(String.Format(CultureInfo.CreateSpecificCulture("da-DK"),
                  "{0:00.00}", value));
// Displays 01,20

value = .086;
Console.WriteLine(value.ToString("#0.##%", CultureInfo.InvariantCulture)); 
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#0.##%}", value)); 
// Displays 8.6%
 
value = 86000;
Console.WriteLine(value.ToString("0.###E+0", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                  "{0:0.###E+0}", value));
 // Displays 8.6E+4
Dim value As Double

value = 1.2
Console.Writeline(value.ToString("0.00", CultureInfo.InvariantCulture))
Console.Writeline(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0.00}", value))
' Displays 1.20

Console.WriteLine(value.ToString("00.00", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:00.00}", value))
' Displays 01.20

Console.WriteLine(value.ToString("00.00", _
                  CultureInfo.CreateSpecificCulture("da-DK")))
Console.WriteLine(String.Format(CultureInfo.CreateSpecificCulture("da-DK"),
                  "{0:00.00}", value))
' Displays 01,20

value = .086
Console.WriteLine(value.ToString("#0.##%", CultureInfo.InvariantCulture)) 
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#0.##%}", value)) 
' Displays 8.6%
 
value = 86000
Console.WriteLine(value.ToString("0.###E+0", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                  "{0:0.###E+0}", value))
 ' Displays 8.6E+4

回到表格Back to table

"," 自訂規範The "," custom specifier

"," 字元同時當做群組分隔符號和數值縮放規範。The "," character serves as both a group separator and a number scaling specifier.

  • 群組分隔符號:如果在用於格式化數字整數位數的兩個數字預留位置 (0 或 #) 之間指定一或多個逗號,則會在輸出的整數部分中在每個數字群組之間插入群組分隔符號字元。Group separator: If one or more commas are specified between two digit placeholders (0 or #) that format the integral digits of a number, a group separator character is inserted between each number group in the integral part of the output.

    目前 NumberGroupSeparator 物件的 NumberGroupSizesNumberFormatInfo 屬性會判斷當做數字群組分隔符號使用的字元,以及每個數字群組的大小。The NumberGroupSeparator and NumberGroupSizes properties of the current NumberFormatInfo object determine the character used as the number group separator and the size of each number group. 例如,如果使用字串 "#,#" 和不變的文化特性來格式化數字 1000,則輸出為 "1,000"。For example, if the string "#,#" and the invariant culture are used to format the number 1000, the output is "1,000".

  • 數值縮放規範:如果在明確或隱含小數點的左側緊接著指定一或多個逗號,則每指定一個逗號就會將要格式化的數字除以 1000。Number scaling specifier: If one or more commas are specified immediately to the left of the explicit or implicit decimal point, the number to be formatted is divided by 1000 for each comma. 例如,如果使用字串 "0,," 來格式化數字 1 億,則其輸出為 "100"。For example, if the string "0,," is used to format the number 100 million, the output is "100".

您可以在相同的格式字串內使用群組分隔符號和數值縮放規範。You can use group separator and number scaling specifiers in the same format string. 例如,如果使用字串 "#,0,," 和不變的文化特性來格式化數字 10 億,則輸出為 "1,000"。For example, if the string "#,0,," and the invariant culture are used to format the number one billion, the output is "1,000".

下列範例示範使用逗號做為群組分隔符號。The following example illustrates the use of the comma as a group separator.

double value = 1234567890;
Console::WriteLine(value.ToString("#,#", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:#,#}", value));
// Displays 1,234,567,890      

Console::WriteLine(value.ToString("#,##0,,", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:#,##0,,}", value));
// Displays 1,235      	
double value = 1234567890;
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#,#}", value));
// Displays 1,234,567,890      

Console.WriteLine(value.ToString("#,##0,,", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#,##0,,}", value));
// Displays 1,235      	
Dim value As Double = 1234567890
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#,#}", value))
' Displays 1,234,567,890      

Console.WriteLine(value.ToString("#,##0,,", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#,##0,,}", value))
' Displays 1,235      	

下列範例示範使用逗點做為數值縮放的規範。The following example illustrates the use of the comma as a specifier for number scaling.

  double value = 1234567890;
  Console::WriteLine(value.ToString("#,,", CultureInfo::InvariantCulture));	
  Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                  "{0:#,,}", value));	
  // Displays 1235   
  
  Console::WriteLine(value.ToString("#,,,", CultureInfo::InvariantCulture));
  Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                  "{0:#,,,}", value));
// Displays 1  
  
  Console::WriteLine(value.ToString("#,##0,,", CultureInfo::InvariantCulture));       
  Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                  "{0:#,##0,,}", value));       
// Displays 1,235
double value = 1234567890;
Console.WriteLine(value.ToString("#,,", CultureInfo.InvariantCulture));	
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#,,}", value));	
// Displays 1235   

Console.WriteLine(value.ToString("#,,,", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#,,,}", value));
// Displays 1  

Console.WriteLine(value.ToString("#,##0,,", CultureInfo.InvariantCulture));       
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#,##0,,}", value));       
// Displays 1,235
Dim value As Double = 1234567890
Console.WriteLine(value.ToString("#,,", CultureInfo.InvariantCulture))	
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0:#,,}", value))	
' Displays 1235   

Console.WriteLine(value.ToString("#,,,", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#,,,}", value))
 ' Displays 1  

Console.WriteLine(value.ToString("#,##0,,", CultureInfo.InvariantCulture))       
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#,##0,,}", value))       
 ' Displays 1,235

回到表格Back to table

"%" 自訂規範The "%" custom specifier

格式字串中的百分比符號 (%) 會使得數字在格式化之前先乘以 100。A percent sign (%) in a format string causes a number to be multiplied by 100 before it is formatted. 數字中會根據格式字串中出現 % 的位置,插入當地語系化百分比符號。The localized percent symbol is inserted in the number at the location where the % appears in the format string. 使用的百分比字元由目前 PercentSymbol 物件的 NumberFormatInfo 屬性所定義。The percent character used is defined by the PercentSymbol property of the current NumberFormatInfo object.

下列範例會定義幾個包含 "%" 自訂規範的自訂格式字串。The following example defines several custom format strings that include the "%" custom specifier.

double value = .086;
Console::WriteLine(value.ToString("#0.##%", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:#0.##%}", value));
// Displays 8.6%      
double value = .086;
Console.WriteLine(value.ToString("#0.##%", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#0.##%}", value));
// Displays 8.6%      
Dim value As Double = .086
Console.WriteLine(value.ToString("#0.##%", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:#0.##%}", value))
' Displays 8.6%      

回到表格Back to table

"‰" 自訂規範The "‰" custom specifier

格式字串中的千分比字元 (‰ 或 \u2030) 會使得數字在格式化之前先乘以 1000。A per mille character (‰ or \u2030) in a format string causes a number to be multiplied by 1000 before it is formatted. 傳回的字串中會根據格式字串中出現 ‰ 符號的位置,插入適當的千分比符號。The appropriate per mille symbol is inserted in the returned string at the location where the ‰ symbol appears in the format string. 使用的千分之一符號字元是由提供文化特性特定格式資訊之物件的 NumberFormatInfo.PerMilleSymbol 屬性定義的。The per mille character used is defined by the NumberFormatInfo.PerMilleSymbol property of the object that provides culture-specific formatting information.

下列範例會定義包含 "‰" 自訂規範的自訂格式字串。The following example defines a custom format string that includes the "‰" custom specifier.

double value = .00354;
String^ perMilleFmt = "#0.## " + '\u2030';
Console::WriteLine(value.ToString(perMilleFmt, CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:" + perMilleFmt + "}", value));
// Displays 3.54‰      
double value = .00354;
string perMilleFmt = "#0.## " + '\u2030';
Console.WriteLine(value.ToString(perMilleFmt, CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:" + perMilleFmt + "}", value));
// Displays 3.54‰      
Dim value As Double = .00354
Dim perMilleFmt As String = "#0.## " & ChrW(&h2030)
Console.WriteLine(value.ToString(perMilleFmt, CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:" + perMilleFmt + "}", value))
' Displays 3.54 ‰      

回到表格Back to table

"E" 和 "e" 自訂規範The "E" and "e" custom specifiers

如果 "E"、"E+"、"E-"、"e"、"e+" 或 "e-" 中的任何一個字串出現在格式字串中,且後面至少緊接著一個零,則會使用科學標記法來格式化數字,並在數字和指數之間插入 "E" 或 "e"。If any of the strings "E", "E+", "E-", "e", "e+", or "e-" are present in the format string and are followed immediately by at least one zero, the number is formatted by using scientific notation with an "E" or "e" inserted between the number and the exponent. 接在科學標記法指標之後的零個數決定要在指數部分輸出的最少位數。The number of zeros following the scientific notation indicator determines the minimum number of digits to output for the exponent. "E+" 和 "e+" 格式表示指數前面應該一律加上加號或減號。The "E+" and "e+" formats indicate that a plus sign or minus sign should always precede the exponent. "E"、"E-"、"e" 或 "e-" 格式表示只應該在負數指數前面加上正負號字元。The "E", "E-", "e", or "e-" formats indicate that a sign character should precede only negative exponents.

下列範例使用科學記號規範來格式化幾個數值。The following example formats several numeric values using the specifiers for scientific notation.

double value = 86000;
Console::WriteLine(value.ToString("0.###E+0", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:0.###E+0}", value));
// Displays 8.6E+4

Console::WriteLine(value.ToString("0.###E+000", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:0.###E+000}", value));
// Displays 8.6E+004

Console::WriteLine(value.ToString("0.###E-000", CultureInfo::InvariantCulture));
Console::WriteLine(String::Format(CultureInfo::InvariantCulture, 
                                "{0:0.###E-000}", value));
// Displays 8.6E004
double value = 86000;
Console.WriteLine(value.ToString("0.###E+0", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0.###E+0}", value));
// Displays 8.6E+4

Console.WriteLine(value.ToString("0.###E+000", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0.###E+000}", value));
// Displays 8.6E+004

Console.WriteLine(value.ToString("0.###E-000", CultureInfo.InvariantCulture));
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0.###E-000}", value));
// Displays 8.6E004
Dim value As Double = 86000
Console.WriteLine(value.ToString("0.###E+0", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0.###E+0}", value))
' Displays 8.6E+4

Console.WriteLine(value.ToString("0.###E+000", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0.###E+000}", value))
' Displays 8.6E+004

Console.WriteLine(value.ToString("0.###E-000", CultureInfo.InvariantCulture))
Console.WriteLine(String.Format(CultureInfo.InvariantCulture, 
                                "{0:0.###E-000}", value))
' Displays 8.6E004

回到表格Back to table

"\" 逸出字元The "\" escape character

格式字串中的 "#"、"0"、"."、","、"%" 和 "‰" 符號會解譯為格式規範,而不是常值字元。The "#", "0", ".", ",", "%", and "‰" symbols in a format string are interpreted as format specifiers rather than as literal characters. 大寫和小寫 "E" 以及 + 和 - 符號視其在自訂格式字串中的位置而定,也有可能會解譯為格式規範。Depending on their position in a custom format string, the uppercase and lowercase "E" as well as the + and - symbols may also be interpreted as format specifiers.

若要避免將字元解譯為格式規範,您可以在前面加上反斜線,這是逸出字元。To prevent a character from being interpreted as a format specifier, you can precede it with a backslash, which is the escape character. 逸出字元表示接下來的字元是字元常值,應該原封不動地放入結果字串中。The escape character signifies that the following character is a character literal that should be included in the result string unchanged.

若要在結果字串中加上反斜線,您必須再加上一個反斜線 (變成\\),才能將反斜線解譯為常值。To include a backslash in a result string, you must escape it with another backslash (\\).

注意

某些編譯器 (例如 C++ 和 C# 編譯器) 也可能會將單一反斜線字元解譯為逸出字元。Some compilers, such as the C++ and C# compilers, may also interpret a single backslash character as an escape character. 為了確保字串在格式化時能夠正確獲得解譯,您可以在 C# 中的字串前面加上逐字字串常值字元 (@ 字元),或在 C# 和 C++ 中的每個反斜線前面再加上一個反斜線字元。To ensure that a string is interpreted correctly when formatting, you can use the verbatim string literal character (the @ character) before the string in C#, or add another backslash character before each backslash in C# and C++. 下列 C# 範例示範這兩種做法。The following C# example illustrates both approaches.

下列範例會使用逸出字元,以避免格式化作業將 "#"、"0" 和 "\" 字元解譯為逸出字元或格式規範。The following example uses the escape character to prevent the formatting operation from interpreting the "#", "0", and "\" characters as either escape characters or format specifiers. C# 範例會多使用一個反斜線,以確保反斜線會解譯為常值字元。The C# examples uses an additional backslash to ensure that a backslash is interpreted as a literal character.

int value = 123;
Console::WriteLine(value.ToString("\\#\\#\\# ##0 dollars and \\0\\0 cents \\#\\#\\#"));
Console::WriteLine(String::Format("{0:\\#\\#\\# ##0 dollars and \\0\\0 cents \\#\\#\\#}",
                                  value));
// Displays ### 123 dollars and 00 cents ###

Console::WriteLine(value.ToString("\\#\\#\\# ##0 dollars and \0\0 cents \\#\\#\\#"));
Console::WriteLine(String::Format("{0:\\#\\#\\# ##0 dollars and \0\0 cents \\#\\#\\#}",
                                value));
// Displays ### 123 dollars and 00 cents ###

Console::WriteLine(value.ToString("\\\\\\\\\\\\ ##0 dollars and \\0\\0 cents \\\\\\\\\\\\"));
Console::WriteLine(String::Format("{0:\\\\\\\\\\\\ ##0 dollars and \\0\\0 cents \\\\\\\\\\\\}",
                                value));
// Displays \\\ 123 dollars and 00 cents \\\

Console::WriteLine(value.ToString("\\\\\\ ##0 dollars and \0\0 cents \\\\\\"));
Console::WriteLine(String::Format("{0:\\\\\\ ##0 dollars and \0\0 cents \\\\\\}",
                                value));
// Displays \\\ 123 dollars and 00 cents \\\
int value = 123;
Console.WriteLine(value.ToString("\\#\\#\\# ##0 dollars and \\0\\0 cents \\#\\#\\#"));
Console.WriteLine(String.Format("{0:\\#\\#\\# ##0 dollars and \\0\\0 cents \\#\\#\\#}",
                                value));
// Displays ### 123 dollars and 00 cents ###

Console.WriteLine(value.ToString(@"\#\#\# ##0 dollars and \0\0 cents \#\#\#"));
Console.WriteLine(String.Format(@"{0:\#\#\# ##0 dollars and \0\0 cents \#\#\#}",
                                value));
// Displays ### 123 dollars and 00 cents ###

Console.WriteLine(value.ToString("\\\\\\\\\\\\ ##0 dollars and \\0\\0 cents \\\\\\\\\\\\"));
Console.WriteLine(String.Format("{0:\\\\\\\\\\\\ ##0 dollars and \\0\\0 cents \\\\\\\\\\\\}",
                                value));
// Displays \\\ 123 dollars and 00 cents \\\

Console.WriteLine(value.ToString(@"\\\\\\ ##0 dollars and \0\0 cents \\\\\\"));
Console.WriteLine(String.Format(@"{0:\\\\\\ ##0 dollars and \0\0 cents \\\\\\}",
                                value));
// Displays \\\ 123 dollars and 00 cents \\\
Dim value As Integer = 123
Console.WriteLine(value.ToString("\#\#\# ##0 dollars and \0\0 cents \#\#\#"))
Console.WriteLine(String.Format("{0:\#\#\# ##0 dollars and \0\0 cents \#\#\#}", 
                                value))
' Displays ### 123 dollars and 00 cents ###

Console.WriteLine(value.ToString("\\\\\\ ##0 dollars and \0\0 cents \\\\\\"))
Console.WriteLine(String.Format("{0:\\\\\\ ##0 dollars and \0\0 cents \\\\\\}", 
                                value))
' Displays \\\ 123 dollars and 00 cents \\\

回到表格Back to table

";" 區段分隔符號The ";" section separator

冒號 (;) 是條件式格式規範,這個規範會根據數字的值是正數、負數還是零,將不同的格式套用至數字。The semicolon (;) is a conditional format specifier that applies different formatting to a number depending on whether its value is positive, negative, or zero. 若要產生這個行為,自訂格式字串可以包含多達三個以分號分隔的區段,To produce this behavior, a custom format string can contain up to three sections separated by semicolons. 下表將說明這些區段。These sections are described in the following table.

區段數Number of sections 說明Description
一個區段One section 此格式字串適用於所有的值。The format string applies to all values.
兩個區段Two sections 第一個區段適用於正數值及零值,第二個區段適用於負數值。The first section applies to positive values and zeros, and the second section applies to negative values.

如果要格式化的數字為負數,但依照第二個區段的格式四捨五入之後成為零,則產生的零會依照第一個區段來格式化。If the number to be formatted is negative, but becomes zero after rounding according to the format in the second section, the resulting zero is formatted according to the first section.
三個區段Three sections 第一個區段適用於正數值,第二個區段適用於負數值,而第三個區段則適用於零值。The first section applies to positive values, the second section applies to negative values, and the third section applies to zeros.

第二個區段可留白 (分號之間沒有任何內容),此時第一個區段將套用到所有非零值。The second section can be left empty (by having nothing between the semicolons), in which case the first section applies to all nonzero values.

如果要格式化的數字不是零,但依照第一個或第二個區段的格式四捨五入之後成為零,則產生的零會依照第三個區段來格式化。If the number to be formatted is nonzero, but becomes zero after rounding according to the format in the first or second section, the resulting zero is formatted according to the third section.

區段分隔符號會在最終值已格式化時,忽略任何事先存在而與數值相關的格式。Section separators ignore any preexisting formatting associated with a number when the final value is formatted. 例如,負數值在使用區段分隔符號時永遠不以負號來顯示。For example, negative values are always displayed without a minus sign when section separators are used. 如果您想要最終的格式化值具有負號,您應該明確包含負號做為自訂格式規範的一部分。If you want the final formatted value to have a minus sign, you should explicitly include the minus sign as part of the custom format specifier.

下列範例會使用 ";" 格式規範,以不同方式格式化正數、負數和零。The following example uses the ";" format specifier to format positive, negative, and zero numbers differently.

double posValue = 1234;
double negValue = -1234;
double zeroValue = 0;

String^ fmt2 = "##;(##)";
String^ fmt3 = "##;(##);**Zero**";

Console::WriteLine(posValue.ToString(fmt2));  
Console::WriteLine(String::Format("{0:" + fmt2 + "}", posValue));    
// Displays 1234

Console::WriteLine(negValue.ToString(fmt2));  
Console::WriteLine(String::Format("{0:" + fmt2 + "}", negValue));    
// Displays (1234)

Console::WriteLine(zeroValue.ToString(fmt3)); 
Console::WriteLine(String::Format("{0:" + fmt3 + "}", zeroValue));
// Displays **Zero**
double posValue = 1234;
double negValue = -1234;
double zeroValue = 0;

string fmt2 = "##;(##)";
string fmt3 = "##;(##);**Zero**";

Console.WriteLine(posValue.ToString(fmt2));  
Console.WriteLine(String.Format("{0:" + fmt2 + "}", posValue));    
// Displays 1234

Console.WriteLine(negValue.ToString(fmt2));  
Console.WriteLine(String.Format("{0:" + fmt2 + "}", negValue));    
// Displays (1234)

Console.WriteLine(zeroValue.ToString(fmt3)); 
Console.WriteLine(String.Format("{0:" + fmt3 + "}", zeroValue));
// Displays **Zero**
Dim posValue As Double = 1234
Dim negValue As Double = -1234
Dim zeroValue As Double = 0

Dim fmt2 As String = "##;(##)"
Dim fmt3 As String = "##;(##);**Zero**"

Console.WriteLine(posValue.ToString(fmt2))   
Console.WriteLine(String.Format("{0:" + fmt2 + "}", posValue))    
' Displays 1234

Console.WriteLine(negValue.ToString(fmt2))   
Console.WriteLine(String.Format("{0:" + fmt2 + "}", negValue))    
' Displays (1234)

Console.WriteLine(zeroValue.ToString(fmt3))  
Console.WriteLine(String.Format("{0:" + fmt3 + "}", zeroValue))
' Displays **Zero**

回到表格Back to table

字元常值Character literals

自訂數值格式字串中出現的格式規範一律會解譯為格式字元,永遠不會解譯為常值字元。Format specifiers that appear in a custom numeric format string are always interpreted as formatting characters and never as literal characters. 這包含下列字元:This includes the following characters:

所有其他字元一律會解譯為字元常值,並在格式化作業中,原封不動地包含在結果字串中。All other characters are always interpreted as character literals and, in a formatting operation, are included in the result string unchanged. 在剖析作業中,它們必須完全符合輸入字串中的字元;這項比較會區分大小寫。In a parsing operation, they must match the characters in the input string exactly; the comparison is case-sensitive.

下列範例說明常值字元單位 (在此案例中為千分位) 的一個常見用法:The following example illustrates one common use of literal character units (in this case, thousands):

double n = 123.8;
Console.WriteLine($"{n:#,##0.0K}");
// The example displays the following output:
//      123.8K   
Dim n As Double = 123.8
Console.WriteLine($"{n:#,##0.0K}")
' The example displays the following output:
'       123.8K

您可以使用兩種方式來指定將字元解譯為常值字元,而不是格式字元,以便包含在結果字串中,或在輸入字串中成功剖析:There are two ways to indicate that characters are to be interpreted as literal characters and not as formatting characters, so that they can be included in a result string or successfully parsed in an input string:

  • 逸出格式字元。By escaping a formatting character. 如需詳細資訊,請參閱 "\" 逸出字元For more information, see The "\" escape character.

  • 以引號括住整個常值字串。By enclosing the entire literal string in quotation apostrophes.

下列範例會使用這兩種方法,在自訂數值格式字串中包含保留的字元。The following example uses both approaches to include reserved characters in a custom numeric format string.

double n = 9.3;
Console.WriteLine($@"{n:##.0\%}");
Console.WriteLine($@"{n:\'##\'}");
Console.WriteLine($@"{n:\\##\\}");
Console.WriteLine();
Console.WriteLine($"{n:##.0'%'}");
Console.WriteLine($@"{n:'\'##'\'}");
// The example displays the following output:
//      9.3%
//      '9'
//      \9\
//
//      9.3%
//      \9\
Dim n As Double = 9.3
Console.WriteLine($"{n:##.0\%}") 
Console.WriteLine($"{n:\'##\'}")
Console.WriteLine($"{n:\\##\\}")
Console.WriteLine()
Console.WriteLine($"{n:##.0'%'}")
Console.WriteLine($"{n:'\'##'\'}")
' The example displays the following output:
'      9.3%
'      '9'
'      \9\
'
'      9.3%
'      \9\

注意Notes

無限浮點數和 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 specified by the currently applicable NumberFormatInfo object.

控制台設定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, and the current thread culture provides values used to govern formatting. 使用不同設定的電腦會產生不同的結果字串。Computers that use different settings generate different result strings.

此外,如果您使用 CultureInfo.CultureInfo(String) 建構函式來具現化新的 CultureInfo 物件,而此物件代表的文化特性與目前系統文化特性相同,則 [控制台] 中的 [ 地區及語言選項 ] 項目所建立的任何自訂都會套用至新的 CultureInfo 物件。In addition, if you use the CultureInfo.CultureInfo(String) constructor 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.

四捨五入和定點格式字串Rounding and fixed-point format strings

如果是定點格式字串 (即不含科學標記法格式字元的格式字串),則數字會四捨五入成與小數點右邊之數字預留位置一樣多的小數位數。For fixed-point format strings (that is, format strings that do not contain scientific notation format characters), numbers are rounded to as many decimal places as there are digit placeholders to the right of the decimal point. 如果格式字串不包含小數點,數值四捨五入至最接近的整數。If the format string does not contain a decimal point, the number is rounded to the nearest integer. 如果數值有比小數點左邊的數字預留位置還要多的位數,額外位數會緊接第一個數字預留位置之前複製到輸出字串。If the number has more digits than there are digit placeholders to the left of the decimal point, the extra digits are copied to the result string immediately before the first digit placeholder.

回到表格Back to table

範例Example

下列範例示範兩個自訂數值格式字串。The following example demonstrates two custom numeric format strings. 在這兩個範例中,數字預留位置 (#) 會顯示數值資料,而所有其他字元則會複製到結果字串中。In both cases, the digit placeholder (#) displays the numeric data, and all other characters are copied to the result string.

double number1 = 1234567890;
String^ value1 = number1.ToString("(###) ###-####");
Console::WriteLine(value1);

int number2 = 42;
String^ value2 = number2.ToString("My Number = #");
Console::WriteLine(value2);
// The example displays the following output:
//       (123) 456-7890
//       My Number = 42
double number1 = 1234567890;
string value1 = number1.ToString("(###) ###-####");
Console.WriteLine(value1);

int number2 = 42;
string value2 = number2.ToString("My Number = #");
Console.WriteLine(value2);
// The example displays the following output:
//       (123) 456-7890
//       My Number = 42
Dim number1 As Double = 1234567890
Dim value1 As String = number1.ToString("(###) ###-####")
Console.WriteLine(value1)

Dim number2 As Integer = 42
Dim value2 As String = number2.ToString("My Number = #")
Console.WriteLine(value2)
' The example displays the following output:
'       (123) 456-7890
'       My Number = 42

回到表格Back to table

另請參閱See also