自定义数字格式字符串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.

提示

可以下载格式设置实用工具,通过该应用程序,可将格式字符串应用于数值或日期和时间值并显示结果字符串。You can download the Formatting Utility, an application that enables you to apply format strings to either numeric or date and time values and displays the result string.

下表描述自定义数字格式说明符并显示由每个格式说明符产生的示例输出。The following table describes the 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 nameName 描述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""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.

备注

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. The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

The current culture of the Try.NET inline code runner and playground is the invariant culture. As a result, the output produced by the inline code runner differs from the output displayed by examples that use a default culture as the current culture.

You can work around this limitation by adding a line of code like the following to set the culture: System.Globalization.CultureInfo.CurrentCulture = new System.Globalization.CultureInfo("en-US"); Just replace en-US with the name of the culture that you'd like to be the current culture.

“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,,”对数字 100000000 进行格式化,则输出为“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,,”和固定区域性对数字 1000000000 进行格式化,则输出为“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.

 [!code-csharp-interactive[including reserved characters](~/samples/snippets/csharp/VS_Snippets_CLR/formatting.numeric.custom/cs/literal1.cs#1)]
 [!code-vb[including reserved characters](~/samples/snippets/visualbasic/VS_Snippets_CLR/formatting.numeric.custom/vb/literal1.vb#1)]  

说明Notes

浮点型无穷大和 NaNFloating-Point infinities and NaN

无论格式字符串原来是什么值,只要 SingleDouble 浮点类型的值为正无穷大、负无穷大或非数值 (NaN),格式字符串就分别是当前适用的 PositiveInfinitySymbol对象指定的 NegativeInfinitySymbolNaNSymbolNumberFormatInfo 属性的值。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

System.Globalization.NumberFormatInfo
格式设置类型Formatting Types
Standard Numeric Format StringsStandard Numeric Format Strings
如何:用前导零填充数字How to: Pad a Number with Leading Zeros
示例:.NET Framework 4 格式设置实用工具Sample: .NET Framework 4 Formatting Utility