标准数字格式字符串Standard Numeric Format Strings

标准数字格式字符串用于格式化通用数值类型。Standard numeric format strings are used to format common numeric types. 标准数字格式字符串采用 Axx 的形式,其中:A standard numeric format string takes the form Axx, where:

  • A 是称为“格式说明符” 的单个字母字符。A is a single alphabetic character called the format specifier. 任何包含一个以上字母字符(包括空白)的数字格式字符串都被解释为自定义数字格式字符串。Any numeric format string that contains more than one alphabetic character, including white space, is interpreted as a custom numeric format string. 有关更多信息,请参见自定义数字格式字符串For more information, see Custom Numeric Format Strings.

  • xx 是称为“精度说明符” 的可选整数。xx is an optional integer called the precision specifier. 精度说明符的范围从 0 到 99,并且影响结果中的位数。The precision specifier ranges from 0 to 99 and affects the number of digits in the result. 请注意,精度说明符控制数字的字符串表示形式中的数字个数。Note that the precision specifier controls the number of digits in the string representation of a number. 它不舍入该数字。It does not round the number itself. 若要执行舍入运算,请使用 Math.CeilingMath.FloorMath.Round 方法。To perform a rounding operation, use the Math.Ceiling, Math.Floor, or Math.Round method.

    当精度说明符控制结果字符串中的小数位数时,结果字符串会反映一个数字,该数字四舍五入到最接近无限精确结果的可表示结果 。When precision specifier controls the number of fractional digits in the result string, the result string reflects a number that is rounded to a representable result nearest to the infinitely precise result. 如果有两个同样接近的可表示结果:If there are two equally near representable results:

    • 在 .NET Framework 和.NET Core(.NET Core 2.0 及以下)上,运行时选择最低有效数字更高的结果(即使用 MidpointRounding.AwayFromZero) 。On the .NET Framework and .NET Core up to .NET Core 2.0, the runtime selects the result with the greater least significant digit (that is, using MidpointRounding.AwayFromZero).
    • 在 .NET Core 2.1 及更高版本上,运行时选择最低有效数字为偶数的结果(即使用 MidpointRounding.ToEven) 。On .NET Core 2.1 and later, the runtime selects the result with an even least significant digit (that is, using MidpointRounding.ToEven).

    备注

    精度说明符确定结果字符串中的位数。The precision specifier determines the number of digits in the result string. 若要使用前导或尾随空格填充结果字符串,请使用复合格式设置功能,并在格式项中定义对齐组件To pad a result string with leading or trailing spaces, use the composite formatting feature and define an alignment component in the format item.

下列支持标准数字格式字符串:Standard numeric format strings are supported by:

提示

你可以下载格式设置实用工具,它属于一种 .NET Core Windows 窗体应用程序,通过该应用程序,你可将格式字符串应用于数值或日期和时间值并显示结果字符串 。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 BasicSource code is available for C# and Visual Basic.

下表介绍标准数字格式说明符并显示每个格式说明符产生的示例输出。The following table describes the standard numeric format specifiers and displays sample output produced by each format specifier. 有关使用标准数字格式字符串的其他信息,请参见注释一节;有关使用方法的完整演示,请参见示例一节。See the Notes section for additional information about using standard numeric format strings, and the Example section for a comprehensive illustration of their use.

格式说明符Format specifier nameName 说明Description 示例Examples
“C”或“c”"C" or "c" 货币Currency 结果:货币值。Result: A currency value.

受以下类型支持:所有数值类型。Supported by: All numeric types.

精度说明符:十进制小数位数。Precision specifier: Number of decimal digits.

默认值精度说明符:由 NumberFormatInfo.CurrencyDecimalDigits 定义。Default precision specifier: Defined by NumberFormatInfo.CurrencyDecimalDigits.

更多信息:货币(“C”)格式说明符More information: The Currency ("C") Format Specifier.
123.456 ("C", en-US) -> \$123.46123.456 ("C", en-US) -> \$123.46

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

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

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

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

-123.456 ("C3", ja-JP) -> -¥123.456-123.456 ("C3", ja-JP) -> -¥123.456
“D”或“d”"D" or "d" 十进制Decimal 结果:整型数字,负号可选。Result: Integer digits with optional negative sign.

受以下类型支持:仅限整型类型。Supported by: Integral types only.

精度说明符:数字位数下限。Precision specifier: Minimum number of digits.

默认值精度说明符:所需数字位数下限。Default precision specifier: Minimum number of digits required.

更多信息:十进制(“D”)格式说明符More information: The Decimal("D") Format Specifier.
1234 ("D") -> 12341234 ("D") -> 1234

-1234 ("D6") -> -001234-1234 ("D6") -> -001234
“E”或“e”"E" or "e" 指数(科学型)Exponential (scientific) 结果:指数表示法。Result: Exponential notation.

受以下类型支持:所有数值类型。Supported by: All numeric types.

精度说明符:十进制小数位数。Precision specifier: Number of decimal digits.

默认值精度说明符:6.Default precision specifier: 6.

更多信息:指数(“E”)格式说明符More information: The Exponential ("E") Format Specifier.
1052.0329112756 ("E", en-US) -> 1.052033E+0031052.0329112756 ("E", en-US) -> 1.052033E+003

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

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

-1052.0329112756 ("E2", fr-FR) -> -1,05E+003-1052.0329112756 ("E2", fr-FR) -> -1,05E+003
“F”或“f”"F" or "f" 定点Fixed-point 结果:整数和十进制小数,负号可选。Result: Integral and decimal digits with optional negative sign.

受以下类型支持:所有数值类型。Supported by: All numeric types.

精度说明符:十进制小数位数。Precision specifier: Number of decimal digits.

默认值精度说明符:由 NumberFormatInfo.NumberDecimalDigits 定义。Default precision specifier: Defined by NumberFormatInfo.NumberDecimalDigits.

更多信息:定点(“F”)格式说明符More information: The Fixed-Point ("F") Format Specifier.
1234.567 ("F", en-US) -> 1234.571234.567 ("F", en-US) -> 1234.57

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

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

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

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

-1234.56 ("F4", de-DE) -> -1234,5600-1234.56 ("F4", de-DE) -> -1234,5600
“G”或“g”"G" or "g" 常规General 结果:更紧凑的定点表示法或科学记数法。Result: The more compact of either fixed-point or scientific notation.

受以下类型支持:所有数值类型。Supported by: All numeric types.

精度说明符:有效位数。Precision specifier: Number of significant digits.

默认值精度说明符:具体取决于数值类型。Default precision specifier: Depends on numeric type.

更多信息:常规(“G”)格式说明符More information: The General ("G") Format Specifier.
-123.456 ("G", en-US) -> -123.456-123.456 ("G", en-US) -> -123.456

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

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

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

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

-1.234567890e-25 ("G", sv-SE) -> -1,23456789E-25-1.234567890e-25 ("G", sv-SE) -> -1,23456789E-25
“N”或“n”"N" or "n" 数字Number 结果:整数和十进制小数、组分隔符和十进制小数分隔符,负号可选。Result: Integral and decimal digits, group separators, and a decimal separator with optional negative sign.

受以下类型支持:所有数值类型。Supported by: All numeric types.

精度说明符:所需的小数位数。Precision specifier: Desired number of decimal places.

默认值精度说明符:由 NumberFormatInfo.NumberDecimalDigits 定义。Default precision specifier: Defined by NumberFormatInfo.NumberDecimalDigits.

更多信息:数字(“N”)格式说明符More information: The Numeric ("N") Format Specifier.
1234.567 ("N", en-US) -> 1,234.571234.567 ("N", en-US) -> 1,234.57

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

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

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

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

-1234.56 ("N3", ru-RU) -> -1 234,560-1234.56 ("N3", ru-RU) -> -1 234,560
“P”或“p”"P" or "p" 百分比Percent 结果:数字乘以 100 并以百分比符号显示。Result: Number multiplied by 100 and displayed with a percent symbol.

受以下类型支持:所有数值类型。Supported by: All numeric types.

精度说明符:所需的小数位数。Precision specifier: Desired number of decimal places.

默认值精度说明符:由 NumberFormatInfo.PercentDecimalDigits 定义。Default precision specifier: Defined by NumberFormatInfo.PercentDecimalDigits.

更多信息:百分比(“P”)格式说明符More information: The Percent ("P") Format Specifier.
1 ("P", en-US) -> 100.00 %1 ("P", en-US) -> 100.00 %

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

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

-0.39678 ("P1", fr-FR) -> -39,7 %-0.39678 ("P1", fr-FR) -> -39,7 %
“R”或“r”"R" or "r" 往返过程Round-trip 结果:可以往返至相同数字的字符串。Result: A string that can round-trip to an identical number.

受以下类型支持:SingleDoubleBigIntegerSupported by: Single, Double, and BigInteger.

注意:建议只用于 BigInteger 类型。Note: Recommended for the BigInteger type only. 对于 Double 类型,请使用 "G17";对于 Single 类型,请使用 "G9"。For Double types, use "G17"; for Single types, use "G9".
精度说明符:已忽略。Precision specifier: Ignored.

更多信息:往返过程(“R”)格式说明符More information: The Round-trip ("R") Format Specifier.
123456789.12345678 ("R") -> 123456789.12345678123456789.12345678 ("R") -> 123456789.12345678

-1234567890.12345678 ("R") -> -1234567890.1234567-1234567890.12345678 ("R") -> -1234567890.1234567
“X”或“x”"X" or "x" 十六进制Hexadecimal 结果:十六进制字符串。Result: A hexadecimal string.

受以下类型支持:仅限整型类型。Supported by: Integral types only.

精度说明符:结果字符串中的位数。Precision specifier: Number of digits in the result string.

更多信息:十六进制(“X”)格式说明符More information: The HexaDecimal ("X") Format Specifier.
255 ("X") -> FF255 ("X") -> FF

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

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

-1 ("X4") -> 00FF-1 ("X4") -> 00FF
任何其他单个字符Any other single character 未知说明符Unknown specifier 结果:在运行时引发 FormatExceptionResult: Throws a FormatException at run time.

使用标准数字格式字符串Using Standard Numeric Format Strings

备注

本文中的 C# 示例运行在 Try.NET 内联代码运行程序和演练环境中。The C# examples in this article run in the Try.NET inline code runner and playground. 选择“运行”按钮以在交互窗口中运行示例 。Select the Run button to run an example in an interactive window. 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码 。Once you execute the code, you can modify it and run the modified code by selecting Run again. 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

可采用以下两种方式之一使用标准数字格式字符串定义数值的格式:A standard numeric format string can be used to define the formatting of a numeric value in one of two ways:

  • 可以传递给拥有 ToString 参数的 format 方法的重载。It can be passed to an overload of the ToString method that has a format parameter. 下面的示例将数值的格式设置为当前区域性(在此示例中,为 en-US 区域性)中的货币字符串。The following example formats a numeric value as a currency string in the current culture (in this case, the en-US culture).

    Decimal value = static_cast<Decimal>(123.456);
    Console::WriteLine(value.ToString("C2"));
    // Displays $123.46
    
    decimal value = 123.456m;
    Console.WriteLine(value.ToString("C2"));
    // Displays $123.46
    
    Dim value As Decimal = 123.456d
    Console.WriteLine(value.ToString("C2"))         
    ' Displays $123.46
    
  • 它可作为与 String.FormatConsole.WriteLineStringBuilder.AppendFormat 等方法一起使用的格式项中的 formatString 参数提供。It can be supplied as the formatString argument in a format item used with such methods as String.Format, Console.WriteLine, and StringBuilder.AppendFormat. 有关更多信息,请参见复合格式设置For more information, see Composite Formatting. 下面的示例使用格式项在字符串中插入货币值。The following example uses a format item to insert a currency value in a string.

    Decimal value = static_cast<Decimal>(123.456);
    Console::WriteLine("Your account balance is {0:C2}.", value);
    // Displays "Your account balance is $123.46."
    
    decimal value = 123.456m;
    Console.WriteLine("Your account balance is {0:C2}.", value);
    // Displays "Your account balance is $123.46."
    
    Dim value As Decimal = 123.456d
    Console.WriteLine("Your account balance is {0:C2}.", value)
    ' Displays "Your account balance is $123.46."
    

    可以视需要选择提供 alignment 参数,以指定数字字段宽度以及值是右对齐还是左对齐。Optionally, you can supply an alignment argument to specify the width of the numeric field and whether its value is right- or left-aligned. 下面的示例在 28 位字符的字段中左对齐货币值,在 14 位字符的字段中右对齐货币值。The following example left-aligns a currency value in a 28-character field, and it right-aligns a currency value in a 14-character field.

    array<Decimal>^ amounts = { static_cast<Decimal>(16305.32), 
                                static_cast<Decimal>(18794.16) };
    Console::WriteLine("   Beginning Balance           Ending Balance");
    Console::WriteLine("   {0,-28:C2}{1,14:C2}", amounts[0], amounts[1]);
    // Displays:
    //        Beginning Balance           Ending Balance
    //        $16,305.32                      $18,794.16      
    
    decimal[] amounts = { 16305.32m, 18794.16m };
    Console.WriteLine("   Beginning Balance           Ending Balance");
    Console.WriteLine("   {0,-28:C2}{1,14:C2}", amounts[0], amounts[1]);
    // Displays:
    //        Beginning Balance           Ending Balance
    //        $16,305.32                      $18,794.16      
    
    Dim amounts() As Decimal = { 16305.32d, 18794.16d }
    Console.WriteLine("   Beginning Balance           Ending Balance")
    Console.WriteLine("   {0,-28:C2}{1,14:C2}", amounts(0), amounts(1))
    ' Displays:
    '        Beginning Balance           Ending Balance
    '        $16,305.32                      $18,794.16      
    
  • 可以提供它作为内插字符串的内插表达式项中的 formatString 参数。It can be supplied as the formatString argument in an interpolated expression item of an interpolated string. 有关详细信息,请参阅 C# 参考中的字符串内插主题,或 Visual Basic 参考中的内插字符串主题。For more information, see the String interpolation topic in the C# reference or the Interpolated strings topic in the Visual Basic reference.

以下各节提供有关每个标准数字格式字符串的详细信息。The following sections provide detailed information about each of the standard numeric format strings.

货币(“C”)格式说明符The Currency ("C") Format Specifier

“C”(或货币)格式说明符将数字转换为表示货币金额的字符串。The "C" (or currency) format specifier converts a number to a string that represents a currency amount. 精度说明符指示结果字符串中的所需小数位数。The precision specifier indicates the desired number of decimal places in the result string. 如果省略精度说明符,则默认精度由 NumberFormatInfo.CurrencyDecimalDigits 属性定义。If the precision specifier is omitted, the default precision is defined by the NumberFormatInfo.CurrencyDecimalDigits property.

如果要设置格式的值的小数位数多于指定或默认数量,将在结果字符串中舍入小数值。If the value to be formatted has more than the specified or default number of decimal places, the fractional value is rounded in the result string. 如果指定的小数位数右侧的值大于或等于 5,则结果字符串中的最后一位数将向远离零的一侧舍入。If the value to the right of the number of specified decimal places is 5 or greater, the last digit in the result string is rounded away from zero.

结果字符串受当前 NumberFormatInfo 对象的格式信息的影响。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出了 NumberFormatInfo 属性,这些属性控制返回字符串的格式。The following table lists the NumberFormatInfo properties that control the formatting of the returned string.

NumberFormatInfo 属性NumberFormatInfo property 说明Description
CurrencyPositivePattern 定义正值的货币符号的位置。Defines the placement of the currency symbol for positive values.
CurrencyNegativePattern 定义负值的货币符号的位置,并指定负号由括号表示还是由 NegativeSign 属性表示。Defines the placement of the currency symbol for negative values, and specifies whether the negative sign is represented by parentheses or the NegativeSign property.
NegativeSign 定义在 CurrencyNegativePattern 指明不使用括号时使用的负号。Defines the negative sign used if CurrencyNegativePattern indicates that parentheses are not used.
CurrencySymbol 定义货币符号。Defines the currency symbol.
CurrencyDecimalDigits 定义货币值中的默认小数位数。Defines the default number of decimal digits in a currency value. 可使用精度说明符重写此值。This value can be overridden by using the precision specifier.
CurrencyDecimalSeparator 定义分隔整数位和小数位的字符串。Defines the string that separates integral and decimal digits.
CurrencyGroupSeparator 定义分隔整数的组的字符串。Defines the string that separates groups of integral numbers.
CurrencyGroupSizes 指定在组中显示的整数位数。Defines the number of integer digits that appear in a group.

下面的示例使用货币格式说明符设置 Double 值的格式:The following example formats a Double value with the currency format specifier:

double value = 12345.6789;
Console::WriteLine(value.ToString("C", CultureInfo::CurrentCulture));

Console::WriteLine(value.ToString("C3", CultureInfo::CurrentCulture));

Console::WriteLine(value.ToString("C3", 
                  CultureInfo::CreateSpecificCulture("da-DK")));
// The example displays the following output on a system whose
// current culture is English (United States):
//       $12,345.68
//       $12,345.679
//       kr 12.345,679
double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));

Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));

Console.WriteLine(value.ToString("C3", 
                  CultureInfo.CreateSpecificCulture("da-DK")));
// The example displays the following output on a system whose
// current culture is English (United States):
//       $12,345.68
//       $12,345.679
//       12.345,679 kr
Dim value As Double = 12345.6789
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture))

Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture))

Console.WriteLine(value.ToString("C3", _
                  CultureInfo.CreateSpecificCulture("da-DK")))
' The example displays the following output on a system whose
' current culture is English (United States):
'       $12,345.68
'       $12,345.679
'       kr 12.345,679

返回表首Back to table

十进制(“D”)格式说明符The Decimal ("D") Format Specifier

“D”(或十进制)格式说明符将数字转换为十进制数字 (0-9) 的字符串,如果数字为负,则前面加负号。The "D" (or decimal) format specifier converts a number to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. 只有整型才支持此格式。This format is supported only for integral types.

精度说明符指示结果字符串中所需的最少数字个数。The precision specifier indicates the minimum number of digits desired in the resulting string. 如果需要的话,则用零填充该数字的左侧,以产生精度说明符给定的数字个数。If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. 如果未指定精度说明符,则默认值为表示不带前导零的整数所需的最小值。If no precision specifier is specified, the default is the minimum value required to represent the integer without leading zeros.

结果字符串受当前 NumberFormatInfo 对象的格式信息的影响。The result string is affected by the formatting information of the current NumberFormatInfo object. 如下表所示,一个属性会影响结果字符串的格式。As the following table shows, a single property affects the formatting of the result string.

NumberFormatInfo 属性NumberFormatInfo property 说明Description
NegativeSign 定义指示数字为负值的字符串。Defines the string that indicates that a number is negative.

下面的示例使用十进制格式说明符设置 Int32 值的格式。The following example formats an Int32 value with the decimal format specifier.

int value; 

value = 12345;
Console::WriteLine(value.ToString("D"));
// Displays 12345
Console::WriteLine(value.ToString("D8"));
// Displays 00012345

value = -12345;
Console::WriteLine(value.ToString("D"));
// Displays -12345
Console::WriteLine(value.ToString("D8"));
// Displays -00012345
int value; 

value = 12345;
Console.WriteLine(value.ToString("D"));
// Displays 12345
Console.WriteLine(value.ToString("D8"));
// Displays 00012345

value = -12345;
Console.WriteLine(value.ToString("D"));
// Displays -12345
Console.WriteLine(value.ToString("D8"));
// Displays -00012345
Dim value As Integer 

value = 12345
Console.WriteLine(value.ToString("D"))
' Displays 12345   
Console.WriteLine(value.ToString("D8"))
' Displays 00012345

value = -12345
Console.WriteLine(value.ToString("D"))
' Displays -12345
Console.WriteLine(value.ToString("D8"))
' Displays -00012345

返回表首Back to table

指数(“E”)格式说明符The Exponential ("E") Format Specifier

指数(“E”)格式说明符将数字转换为“-d.ddd…E+ddd”或“-d.ddd…e+ddd”形式的字符串,其中每个“d”表示一个数字 (0-9)。The exponential ("E") format specifier converts a number to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", where each "d" indicates a digit (0-9). 如果该数字为负,则该字符串以减号开头。The string starts with a minus sign if the number is negative. 小数点前总是恰好有一个数字。Exactly one digit always precedes the decimal point.

精度说明符指示小数点后所需的位数。The precision specifier indicates the desired number of digits after the decimal point. 如果省略精度说明符,则使用默认值,即小数点后六位数字。If the precision specifier is omitted, a default of six digits after the decimal point is used.

格式说明符的大小写指示为指数加前缀“E”还是“e”。The case of the format specifier indicates whether to prefix the exponent with an "E" or an "e". 指数总是由正号或负号以及最少三位数字组成。The exponent always consists of a plus or minus sign and a minimum of three digits. 如果需要,用零填充指数以满足最少三位数字的要求。The exponent is padded with zeros to meet this minimum, if required.

结果字符串受当前 NumberFormatInfo 对象的格式信息的影响。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出了 NumberFormatInfo 属性,这些属性控制返回字符串的格式。The following table lists the NumberFormatInfo properties that control the formatting of the returned string.

NumberFormatInfo 属性NumberFormatInfo property 说明Description
NegativeSign 定义表示数字对于系数和指数都为负值的字符串。Defines the string that indicates that a number is negative for both the coefficient and exponent.
NumberDecimalSeparator 定义在系数中将整数位与小数位分隔的字符串。Defines the string that separates the integral digit from decimal digits in the coefficient.
PositiveSign 定义指示指数为正值的字符串。Defines the string that indicates that an exponent is positive.

下面的示例使用指数格式说明符设置 Double 值的格式:The following example formats a Double value with the exponential format specifier:

double value = 12345.6789;
Console::WriteLine(value.ToString("E", CultureInfo::InvariantCulture));
// Displays 1.234568E+004

Console::WriteLine(value.ToString("E10", CultureInfo::InvariantCulture));
// Displays 1.2345678900E+004

Console::WriteLine(value.ToString("e4", CultureInfo::InvariantCulture));
// Displays 1.2346e+004

Console::WriteLine(value.ToString("E", 
                  CultureInfo::CreateSpecificCulture("fr-FR")));
// Displays 1,234568E+004
double value = 12345.6789;
Console.WriteLine(value.ToString("E", CultureInfo.InvariantCulture));
// Displays 1.234568E+004

Console.WriteLine(value.ToString("E10", CultureInfo.InvariantCulture));
// Displays 1.2345678900E+004

Console.WriteLine(value.ToString("e4", CultureInfo.InvariantCulture));
// Displays 1.2346e+004

Console.WriteLine(value.ToString("E", 
                  CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 1,234568E+004
Dim value As Double = 12345.6789
Console.WriteLine(value.ToString("E", CultureInfo.InvariantCulture))
' Displays 1.234568E+004

Console.WriteLine(value.ToString("E10", CultureInfo.InvariantCulture))
' Displays 1.2345678900E+004

Console.WriteLine(value.ToString("e4", CultureInfo.InvariantCulture))
' Displays 1.2346e+004

Console.WriteLine(value.ToString("E", _
                  CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 1,234568E+004

返回表首Back to table

定点(“F”)格式说明符The Fixed-Point ("F") Format Specifier

定点(“F”)格式说明符将数字转换为“-ddd.ddd…”形式的字符串,其中每个“d”表示一个数字 (0-9)。The fixed-point ("F") format specifier converts a number to a string of the form "-ddd.ddd…" where each "d" indicates a digit (0-9). 如果该数字为负,则该字符串以减号开头。The string starts with a minus sign if the number is negative.

精度说明符指示所需的小数位数。The precision specifier indicates the desired number of decimal places. 如果省略精度说明符,则当前 NumberFormatInfo.NumberDecimalDigits 属性提供数值精度。If the precision specifier is omitted, the current NumberFormatInfo.NumberDecimalDigits property supplies the numeric precision.

结果字符串受当前 NumberFormatInfo 对象的格式信息的影响。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出了 NumberFormatInfo 对象的属性,这些属性控制结果字符串的格式。The following table lists the properties of the NumberFormatInfo object that control the formatting of the result string.

NumberFormatInfo 属性NumberFormatInfo property 说明Description
NegativeSign 定义指示数字为负值的字符串。Defines the string that indicates that a number is negative.
NumberDecimalSeparator 定义将整数位与小数位分隔的字符串。Defines the string that separates integral digits from decimal digits.
NumberDecimalDigits 定义默认小数位数。Defines the default number of decimal digits. 可使用精度说明符重写此值。This value can be overridden by using the precision specifier.

下面的示例使用定点格式说明符设置 DoubleInt32 值的格式:The following example formats a Double and an Int32 value with the fixed-point format specifier:

int integerNumber;
integerNumber = 17843;
Console::WriteLine(integerNumber.ToString("F", 
                  CultureInfo::InvariantCulture));
// Displays 17843.00

integerNumber = -29541;
Console::WriteLine(integerNumber.ToString("F3", 
                  CultureInfo::InvariantCulture));
// Displays -29541.000

double doubleNumber;
doubleNumber = 18934.1879;
Console::WriteLine(doubleNumber.ToString("F", CultureInfo::InvariantCulture));
// Displays 18934.19

Console::WriteLine(doubleNumber.ToString("F0", CultureInfo::InvariantCulture));
// Displays 18934

doubleNumber = -1898300.1987;
Console::WriteLine(doubleNumber.ToString("F1", CultureInfo::InvariantCulture));  
// Displays -1898300.2

Console::WriteLine(doubleNumber.ToString("F3", 
                  CultureInfo::CreateSpecificCulture("es-ES")));
// Displays -1898300,199                        
int integerNumber;
integerNumber = 17843;
Console.WriteLine(integerNumber.ToString("F", 
                  CultureInfo.InvariantCulture));
// Displays 17843.00

integerNumber = -29541;
Console.WriteLine(integerNumber.ToString("F3", 
                  CultureInfo.InvariantCulture));
// Displays -29541.000

double doubleNumber;
doubleNumber = 18934.1879;
Console.WriteLine(doubleNumber.ToString("F", CultureInfo.InvariantCulture));
// Displays 18934.19

Console.WriteLine(doubleNumber.ToString("F0", CultureInfo.InvariantCulture));
// Displays 18934

doubleNumber = -1898300.1987;
Console.WriteLine(doubleNumber.ToString("F1", CultureInfo.InvariantCulture));  
// Displays -1898300.2

Console.WriteLine(doubleNumber.ToString("F3", 
                  CultureInfo.CreateSpecificCulture("es-ES")));
// Displays -1898300,199                        
Dim integerNumber As Integer
integerNumber = 17843
Console.WriteLine(integerNumber.ToString("F", CultureInfo.InvariantCulture))
' Displays 17843.00

integerNumber = -29541
Console.WriteLine(integerNumber.ToString("F3", CultureInfo.InvariantCulture))
' Displays -29541.000

Dim doubleNumber As Double
doubleNumber = 18934.1879
Console.WriteLine(doubleNumber.ToString("F", CultureInfo.InvariantCulture))
' Displays 18934.19

Console.WriteLine(doubleNumber.ToString("F0", CultureInfo.InvariantCulture))
' Displays 18934

doubleNumber = -1898300.1987
Console.WriteLine(doubleNumber.ToString("F1", CultureInfo.InvariantCulture))  
' Displays -1898300.2

Console.WriteLine(doubleNumber.ToString("F3", _ 
                  CultureInfo.CreateSpecificCulture("es-ES")))
' Displays -1898300,199                        

返回表首Back to table

常规(“G”)格式说明符The General ("G") Format Specifier

根据数字类型以及是否存在精度说明符,常规(“G”)格式说明符将数字转换为更紧凑的定点表示法或科学记数法。The general ("G") format specifier converts a number to the more compact of either fixed-point or scientific notation, depending on the type of the number and whether a precision specifier is present. 精度说明符定义可以出现在结果字符串中的最大有效位数。The precision specifier defines the maximum number of significant digits that can appear in the result string. 如果精度说明符被省略或为零,则数字的类型决定默认精度,如下表所示。If the precision specifier is omitted or zero, the type of the number determines the default precision, as indicated in the following table.

数值类型Numeric type 默认值精度Default precision
ByteSByteByte or SByte 3 位3 digits
Int16UInt16Int16 or UInt16 5 位5 digits
Int32UInt32Int32 or UInt32 10 位10 digits
Int64 19 位19 digits
UInt64 20 位20 digits
BigInteger 无限制(与“R”相同)Unlimited (same as "R")
Single 7 位7 digits
Double 15 位15 digits
Decimal 29 位29 digits

如果用科学记数法表示数字时指数大于 -5 而且小于精度说明符,则使用定点表示法;否则使用科学记数法。Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and less than the precision specifier; otherwise, scientific notation is used. 结果包含小数点(如果需要),并且忽略小数点后面的尾部零。The result contains a decimal point if required, and trailing zeros after the decimal point are omitted. 如果精度说明符存在,并且结果的有效位数超过指定精度,则通过舍入移除多余的尾部数字。If the precision specifier is present and the number of significant digits in the result exceeds the specified precision, the excess trailing digits are removed by rounding.

但是,如果数字是 Decimal 并且省略精度说明符,将总是使用定点表示法并保留尾部零。However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved.

使用科学记数法时,如果格式说明符是“G”,则结果的指数带前缀“E”;如果格式说明符是“g”,则结果的指数带前缀“e”。If scientific notation is used, the exponent in the result is prefixed with "E" if the format specifier is "G", or "e" if the format specifier is "g". 指数最少包含两个数字。The exponent contains a minimum of two digits. 这与由指数格式说明符生成的科学记数法的格式不同,后者在指数中最少包括三个数字。This differs from the format for scientific notation that is produced by the exponential format specifier, which includes a minimum of three digits in the exponent.

请注意,如果与 Double 值结合使用,"G17" 格式说明符可确保原始 Double 值成功往返。Note that, when used with a Double value, the "G17" format specifier ensures that the original Double value successfully round-trips. 这是因为 Double 是符合 IEEE 754-2008 要求的双精度 (binary64) 浮点数,最高可提供 17 位有效数字的精度。This is because Double is an IEEE 754-2008-compliant double-precision (binary64) floating point number that gives up to 17 significant digits of precision. 建议使用此说明符,而不是 "R" 格式说明符,因为在某些情况下,"R" 无法成功往返双精度浮点值。We recommend its use instead of the "R" format specifier, since in some cases "R" fails to successfully round-trip double-precision floating point values. 下面的示例阐释了这样一种情况。The following example illustrates one such case.

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

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

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

如果与 Single 值结合使用,"G9" 格式说明符可确保原始 Single 值成功往返。When used with a Single value, the "G9" format specifier ensures that the original Single value successfully round-trips. 这是因为 Single 是符合 IEEE 754-2008 要求的但精度 (binary32) 浮点数,最高可提供 9 位有效数字的精度。This is because Single is an IEEE 754-2008-compliant single-precision (binary32) floating point number that gives up to nine significant digits of precision. 出于性能原因,我们建议使用它而不是“R”格式说明符For performance reasons, we recommend its use instead of the "R" format specifier.

结果字符串受当前 NumberFormatInfo 对象的格式信息的影响。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出了 NumberFormatInfo 属性,这些属性控制结果字符串的格式。The following table lists the NumberFormatInfo properties that control the formatting of the result string.

NumberFormatInfo 属性NumberFormatInfo property 说明Description
NegativeSign 定义指示数字为负值的字符串。Defines the string that indicates that a number is negative.
NumberDecimalSeparator 定义将整数位与小数位分隔的字符串。Defines the string that separates integral digits from decimal digits.
PositiveSign 定义指示指数为正值的字符串。Defines the string that indicates that an exponent is positive.

下面的示例使用常规格式说明符设置各种浮点值的格式:The following example formats assorted floating-point values with the general format specifier:

double number;

number = 12345.6789;      
Console::WriteLine(number.ToString("G", CultureInfo::InvariantCulture));
// Displays  12345.6789
Console::WriteLine(number.ToString("G", 
                  CultureInfo::CreateSpecificCulture("fr-FR")));
// Displays 12345,6789
                        
Console::WriteLine(number.ToString("G7", CultureInfo::InvariantCulture));
// Displays 12345.68 

number = .0000023;
Console::WriteLine(number.ToString("G", CultureInfo::InvariantCulture));
// Displays 2.3E-06       
Console::WriteLine(number.ToString("G", 
                  CultureInfo::CreateSpecificCulture("fr-FR")));
// Displays 2,3E-06

number = .0023;
Console::WriteLine(number.ToString("G", CultureInfo::InvariantCulture));
// Displays 0.0023

number = 1234;
Console::WriteLine(number.ToString("G2", CultureInfo::InvariantCulture));
// Displays 1.2E+03

number = Math::PI;
Console::WriteLine(number.ToString("G5", CultureInfo::InvariantCulture));
// Displays 3.1416    
double number;

number = 12345.6789;      
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays  12345.6789
Console.WriteLine(number.ToString("G", 
                  CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 12345,6789
                        
Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture));
// Displays 12345.68 

number = .0000023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 2.3E-06       
Console.WriteLine(number.ToString("G", 
                  CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 2,3E-06

number = .0023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 0.0023

number = 1234;
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));
// Displays 1.2E+03

number = Math.PI;
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));
// Displays 3.1416    
Dim number As Double

number = 12345.6789      
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture))
' Displays  12345.6789
Console.WriteLine(number.ToString("G", _
                  CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 12345,6789
                        
Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture))
' Displays 12345.68 

number = .0000023
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture))
' Displays 2.3E-06       
Console.WriteLine(number.ToString("G", _
                  CultureInfo.CreateSpecificCulture("fr-FR")))
' Displays 2,3E-06

number = .0023
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture))
' Displays 0.0023

number = 1234
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture))
' Displays 1.2E+03

number = Math.Pi
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture))
' Displays 3.1416    

返回表首Back to table

数字(“N”)格式说明符The Numeric ("N") Format Specifier

数字("N")格式说明符将数字转换为"-d,ddd,ddd.ddd…"形式的字符串,其中"-"表示负数符号(如果需要),"d"表示数字 (0-9),","表示组分隔符,"."表示小数点符号。The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" indicates a negative number symbol if required, "d" indicates a digit (0-9), "," indicates a group separator, and "." indicates a decimal point symbol. 精度说明符指示小数点后所需的位数。The precision specifier indicates the desired number of digits after the decimal point. 如果省略精度限定符,则小数位数由当前的 NumberFormatInfo.NumberDecimalDigits 属性来定义。If the precision specifier is omitted, the number of decimal places is defined by the current NumberFormatInfo.NumberDecimalDigits property.

结果字符串受当前 NumberFormatInfo 对象的格式信息的影响。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出了 NumberFormatInfo 属性,这些属性控制结果字符串的格式。The following table lists the NumberFormatInfo properties that control the formatting of the result string.

NumberFormatInfo 属性NumberFormatInfo property 说明Description
NegativeSign 定义指示数字为负值的字符串。Defines the string that indicates that a number is negative.
NumberNegativePattern 定义负值的格式,并指定负号由括号表示还是由 NegativeSign 属性表示。Defines the format of negative values, and specifies whether the negative sign is represented by parentheses or the NegativeSign property.
NumberGroupSizes 指定在组分隔符之间显示的整数位数。Defines the number of integral digits that appear between group separators.
NumberGroupSeparator 定义分隔整数的组的字符串。Defines the string that separates groups of integral numbers.
NumberDecimalSeparator 定义分隔整数位和小数位的字符串。Defines the string that separates integral and decimal digits.
NumberDecimalDigits 定义默认小数位数。Defines the default number of decimal digits. 可使用精度说明符重写此值。This value can be overridden by using a precision specifier.

下面的示例使用数字格式说明符设置各种浮点值的格式:The following example formats assorted floating-point values with the number format specifier:

double dblValue = -12445.6789;
Console::WriteLine(dblValue.ToString("N", CultureInfo::InvariantCulture));
// Displays -12,445.68
Console::WriteLine(dblValue.ToString("N1", 
                  CultureInfo::CreateSpecificCulture("sv-SE")));
// Displays -12 445,7

int intValue = 123456789;
Console::WriteLine(intValue.ToString("N1", CultureInfo::InvariantCulture));
// Displays 123,456,789.0 
double dblValue = -12445.6789;
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture));
// Displays -12,445.68
Console.WriteLine(dblValue.ToString("N1", 
                  CultureInfo.CreateSpecificCulture("sv-SE")));
// Displays -12 445,7

int intValue = 123456789;
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture));
// Displays 123,456,789.0 
Dim dblValue As Double = -12445.6789
Console.WriteLine(dblValue.ToString("N", CultureInfo.InvariantCulture))
' Displays -12,445.68
Console.WriteLine(dblValue.ToString("N1", _
                  CultureInfo.CreateSpecificCulture("sv-SE")))
' Displays -12 445,7

Dim intValue As Integer = 123456789
Console.WriteLine(intValue.ToString("N1", CultureInfo.InvariantCulture))
' Displays 123,456,789.0 

返回表首Back to table

百分比(“P”)格式说明符The Percent ("P") Format Specifier

百分比(“P”)格式说明符将数字乘以 100 并将其转换为表示百分比的字符串。The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage. 精度说明符指示所需的小数位数。The precision specifier indicates the desired number of decimal places. 如果省略精度说明符,则使用当前 PercentDecimalDigits 属性提供的默认数值精度。If the precision specifier is omitted, the default numeric precision supplied by the current PercentDecimalDigits property is used.

下表列出了 NumberFormatInfo 属性,这些属性控制返回字符串的格式。The following table lists the NumberFormatInfo properties that control the formatting of the returned string.

NumberFormatInfo 属性NumberFormatInfo property 说明Description
PercentPositivePattern 定义正值的百分比符号的位置。Defines the placement of the percent symbol for positive values.
PercentNegativePattern 定义负值的百分比符号和负号的位置。Defines the placement of the percent symbol and the negative symbol for negative values.
NegativeSign 定义指示数字为负值的字符串。Defines the string that indicates that a number is negative.
PercentSymbol 定义百分比符号。Defines the percent symbol.
PercentDecimalDigits 定义百分比值中的默认小数位数。Defines the default number of decimal digits in a percentage value. 可使用精度说明符重写此值。This value can be overridden by using the precision specifier.
PercentDecimalSeparator 定义分隔整数位和小数位的字符串。Defines the string that separates integral and decimal digits.
PercentGroupSeparator 定义分隔整数的组的字符串。Defines the string that separates groups of integral numbers.
PercentGroupSizes 指定在组中显示的整数位数。Defines the number of integer digits that appear in a group.

下面的示例使用百分比格式说明符设置浮点值的格式:The following example formats floating-point values with the percent format specifier:

double number = .2468013;
Console::WriteLine(number.ToString("P", CultureInfo::InvariantCulture));
// Displays 24.68 %
Console::WriteLine(number.ToString("P", 
                  CultureInfo::CreateSpecificCulture("hr-HR")));
// Displays 24,68%     
Console::WriteLine(number.ToString("P1", CultureInfo::InvariantCulture));
// Displays 24.7 %
double number = .2468013;
Console.WriteLine(number.ToString("P", CultureInfo.InvariantCulture));
// Displays 24.68 %
Console.WriteLine(number.ToString("P", 
                  CultureInfo.CreateSpecificCulture("hr-HR")));
// Displays 24,68%     
Console.WriteLine(number.ToString("P1", CultureInfo.InvariantCulture));
// Displays 24.7 %
Dim number As Double = .2468013
Console.WriteLine(number.ToString("P", CultureInfo.InvariantCulture))
' Displays 24.68 %
Console.WriteLine(number.ToString("P", _
                  CultureInfo.CreateSpecificCulture("hr-HR")))
' Displays 24,68%     
Console.WriteLine(number.ToString("P1", CultureInfo.InvariantCulture))
' Displays 24.7 %

返回表首Back to table

往返过程(“R”)格式说明符The Round-trip ("R") Format Specifier

往返 ("R") 格式说明符试图确保将转换为字符串的数值分析回相同的数值。The round-trip ("R") format specifier attempts to ensure that a numeric value that is converted to a string is parsed back into the same numeric value. 只有 SingleDoubleBigInteger 类型支持此格式。This format is supported only for the Single, Double, and BigInteger types.

对于 Double 值,某些情况下的“R”格式说明符未能成功往返原始值。For Double values, the "R" format specifier in some cases fails to successfully round-trip the original value. 对于两个 DoubleSingle 值,它还提供相对较差的性能。For both Double and Single values, it also offers relatively poor performance. 建议改用 "G17" 格式说明符以成功往返 Double 值,并改用 "G9" 格式说明符以成功往返 Single 值。Instead, we recommend that you use the "G17" format specifier for Double values and the "G9" format specifier to successfully round-trip Single values.

如果使用此说明符设置 BigInteger 值的格式,其字符串表示形式将包含 BigInteger 值中的所有有效位。When a BigInteger value is formatted using this specifier, its string representation contains all the significant digits in the BigInteger value.

尽管可以包括精度说明符,但会忽略它。Although you can include a precision specifier, it is ignored. 使用此说明符时,往返过程优先于精度。Round trips are given precedence over precision when using this specifier. 结果字符串受当前 NumberFormatInfo 对象的格式信息的影响。The result string is affected by the formatting information of the current NumberFormatInfo object. 下表列出了 NumberFormatInfo 属性,这些属性控制结果字符串的格式。The following table lists the NumberFormatInfo properties that control the formatting of the result string.

NumberFormatInfo 属性NumberFormatInfo property 说明Description
NegativeSign 定义指示数字为负值的字符串。Defines the string that indicates that a number is negative.
NumberDecimalSeparator 定义将整数位与小数位分隔的字符串。Defines the string that separates integral digits from decimal digits.
PositiveSign 定义指示指数为正值的字符串。Defines the string that indicates that an exponent is positive.

下面的示例使用往返格式说明符设置 BigInteger 值的格式。The following example formats a BigInteger value with the round-trip format specifier.

#using <System.Numerics.dll>

using namespace System;
using namespace System::Numerics;

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


using System;
using System.Numerics;

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

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

重要

在某些情况下,如果使用“R”标准数字格式字符串格式化的 Double 值使用 /platform:x64/platform:anycpu 开关编译并在 64 位系统上运行,则该值将无法成功往返。In some cases, Double values formatted with the "R" standard numeric format string do not successfully round-trip if compiled using the /platform:x64 or /platform:anycpu switches and run on 64-bit systems. 有关详细信息,请参阅以下段落。See the following paragraph for more information.

若要解决使用“R”标准数字格式字符串格式化的 Double 值在使用 /platform:x64/platform:anycpu 交换机进行编译并在 64 位系统上运行时所出现的往返不成功的问题,可以使用“G17”标准数字格式字符格式化 Double 值。To work around the problem of Double values formatted with the "R" standard numeric format string not successfully round-tripping if compiled using the /platform:x64 or /platform:anycpu switches and run on 64-bit systems., you can format Double values by using the "G17" standard numeric format string. 以下示例将“R”格式字符串与无法成功往返的 Double 值配合使用,并使用“G17”格式字符串以成功往返原始值:The following example uses the "R" format string with a Double value that does not round-trip successfully, and also uses the "G17" format string to successfully round-trip the original value:

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

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

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

返回表首Back to table

十六进制(“X”)格式说明符The Hexadecimal ("X") Format Specifier

十六进制(“X”)格式说明符将数字转换为十六进制数的字符串。The hexadecimal ("X") format specifier converts a number to a string of hexadecimal digits. 格式说明符的大小写指示对大于 9 的十六进制数使用大写字符还是小写字符。The case of the format specifier indicates whether to use uppercase or lowercase characters for hexadecimal digits that are greater than 9. 例如,使用“X”产生“ABCDEF”,使用“x”产生“abcdef”。For example, use "X" to produce "ABCDEF", and "x" to produce "abcdef". 只有整型才支持此格式。This format is supported only for integral types.

精度说明符指示结果字符串中所需的最少数字个数。The precision specifier indicates the minimum number of digits desired in the resulting string. 如果需要的话,则用零填充该数字的左侧,以产生精度说明符给定的数字个数。If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.

结果字符串不受当前 NumberFormatInfo 对象的格式信息的影响。The result string is not affected by the formatting information of the current NumberFormatInfo object.

下面的示例使用十六进制数法格式说明符设置 Int32 值的格式。The following example formats Int32 values with the hexadecimal format specifier.

int value; 

value = 0x2045e;
Console::WriteLine(value.ToString("x"));
// Displays 2045e
Console::WriteLine(value.ToString("X"));
// Displays 2045E
Console::WriteLine(value.ToString("X8"));
// Displays 0002045E

value = 123456789;
Console::WriteLine(value.ToString("X"));
// Displays 75BCD15
Console::WriteLine(value.ToString("X2"));
// Displays 75BCD15
int value; 

value = 0x2045e;
Console.WriteLine(value.ToString("x"));
// Displays 2045e
Console.WriteLine(value.ToString("X"));
// Displays 2045E
Console.WriteLine(value.ToString("X8"));
// Displays 0002045E

value = 123456789;
Console.WriteLine(value.ToString("X"));
// Displays 75BCD15
Console.WriteLine(value.ToString("X2"));
// Displays 75BCD15
Dim value As Integer 

value = &h2045e
Console.WriteLine(value.ToString("x"))
' Displays 2045e
Console.WriteLine(value.ToString("X"))
' Displays 2045E
Console.WriteLine(value.ToString("X8"))
' Displays 0002045E

value = 123456789
Console.WriteLine(value.ToString("X"))
' Displays 75BCD15
Console.WriteLine(value.ToString("X2"))
' Displays 75BCD15

返回表首Back to table

说明Notes

控制面板设置Control Panel Settings

控制面板中 “区域和语言选项” 项中的设置会影响由格式化操作产生的结果字符串。The settings in the Regional and Language Options item in Control Panel influence the result string produced by a formatting operation. 这些设置用于初始化与当前线程区域性关联的 NumberFormatInfo 对象,当前线程区域性提供用于控制格式设置的值。Those settings are used to initialize the NumberFormatInfo object associated with the current thread culture, which provides values used to govern formatting. 使用不同设置的计算机将生成不同的结果字符串。Computers that use different settings generate different result strings.

此外,如果使用 CultureInfo.CultureInfo(String) 构造函数实例化表示当前系统区域性的新 CultureInfo 对象,通过控制面板中的“区域和语言选项” 项创建的任何自定义都会应用于新 CultureInfo 对象。In addition, if the CultureInfo.CultureInfo(String) constructor is used to instantiate a new CultureInfo object that represents the same culture as the current system culture, any customizations established by the Regional and Language Options item in Control Panel will be applied to the new CultureInfo object. 可以使用 CultureInfo.CultureInfo(String, Boolean) 构造函数来创建不会反映系统的自定义项的 CultureInfo 对象。You can use the CultureInfo.CultureInfo(String, Boolean) constructor to create a CultureInfo object that does not reflect a system's customizations.

NumberFormatInfo 属性NumberFormatInfo Properties

格式设置受当前 NumberFormatInfo 对象的属性影响,它由当前线程区域性隐式提供或由调用格式设置的方法的 IFormatProvider 参数显式提供。Formatting is influenced by the properties of the current NumberFormatInfo object, which is provided implicitly by the current thread culture or explicitly by the IFormatProvider parameter of the method that invokes formatting. 为该参数指定 NumberFormatInfoCultureInfo 对象。Specify a NumberFormatInfo or CultureInfo object for that parameter.

备注

有关自定义用于格式化数值的模式或字符串的信息,请参见 NumberFormatInfo 类主题。For information about customizing the patterns or strings used in formatting numeric values, see the NumberFormatInfo class topic.

整型和浮点型数值类型Integral and Floating-Point Numeric Types

对标准数字格式说明符的一些说明涉及到整型或浮点型数值类型。Some descriptions of standard numeric format specifiers refer to integral or floating-point numeric types. 整型数值类型包括 ByteSByteInt16Int32Int64UInt16UInt32UInt64BigIntegerThe integral numeric types are Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, and BigInteger. 浮点型数值类型有 DecimalSingleDoubleThe floating-point numeric types are Decimal, Single, and Double.

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

无论格式字符串原来是什么值,只要 SingleDouble 浮点类型的值为正无穷大、负无穷大或非数值 (NaN),格式字符串就分别是当前适用的 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 that is specified by the currently applicable NumberFormatInfo object.

示例Example

备注

本文中的一些 C# 示例在 Try.NET 内联代码运行程序和演练环境中运行。Some of the C# examples in this article run in the Try.NET inline code runner and playground. 选择“运行”按钮以在交互窗口中运行示例 。Select the Run button to run an example in an interactive window. 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码 。Once you execute the code, you can modify it and run the modified code by selecting Run again. 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

下面的示例使用 en-US 区域性和所有标准数字格式说明符设置一个整型数值和一个浮点型数值的格式。The following example formats an integral and a floating-point numeric value using the en-US culture and all the standard numeric format specifiers. 此示例使用两个特定的数值类型(DoubleInt32),但对于任何一个其他数值基类型(ByteSByteInt16Int32Int64UInt16UInt32UInt64BigIntegerDecimalSingle)都将产生类似的结果。This example uses two particular numeric types (Double and Int32), but would yield similar results for any of the other numeric base types (Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, BigInteger, Decimal, and Single).

// Display string representations of numbers for en-us culture
CultureInfo ci = new CultureInfo("en-us");

// Output floating point values
double floating = 10761.937554;
Console.WriteLine("C: {0}", 
        floating.ToString("C", ci));           // Displays "C: $10,761.94"
Console.WriteLine("E: {0}", 
        floating.ToString("E03", ci));         // Displays "E: 1.076E+004"
Console.WriteLine("F: {0}", 
        floating.ToString("F04", ci));         // Displays "F: 10761.9376"         
Console.WriteLine("G: {0}",  
        floating.ToString("G", ci));           // Displays "G: 10761.937554"
Console.WriteLine("N: {0}", 
        floating.ToString("N03", ci));         // Displays "N: 10,761.938"
Console.WriteLine("P: {0}", 
        (floating/10000).ToString("P02", ci)); // Displays "P: 107.62 %"
Console.WriteLine("R: {0}", 
        floating.ToString("R", ci));           // Displays "R: 10761.937554"            
Console.WriteLine();

// Output integral values
int integral = 8395;
Console.WriteLine("C: {0}", 
        integral.ToString("C", ci));           // Displays "C: $8,395.00"
Console.WriteLine("D: {0}", 
        integral.ToString("D6", ci));          // Displays "D: 008395" 
Console.WriteLine("E: {0}", 
        integral.ToString("E03", ci));         // Displays "E: 8.395E+003"
Console.WriteLine("F: {0}", 
        integral.ToString("F01", ci));         // Displays "F: 8395.0"    
Console.WriteLine("G: {0}",  
        integral.ToString("G", ci));           // Displays "G: 8395"
Console.WriteLine("N: {0}", 
        integral.ToString("N01", ci));         // Displays "N: 8,395.0"
Console.WriteLine("P: {0}", 
        (integral/10000.0).ToString("P02", ci)); // Displays "P: 83.95 %"
Console.WriteLine("X: 0x{0}", 
        integral.ToString("X", ci));           // Displays "X: 0x20CB"
Console.WriteLine();
Option Strict On

Imports System.Globalization
Imports System.Threading

Module NumericFormats
   Public Sub Main()
      ' Display string representations of numbers for en-us culture
      Dim ci As New CultureInfo("en-us")
      
      ' Output floating point values
      Dim floating As Double = 10761.937554
      Console.WriteLine("C: {0}", _
              floating.ToString("C", ci))           ' Displays "C: $10,761.94"
      Console.WriteLine("E: {0}", _
              floating.ToString("E03", ci))         ' Displays "E: 1.076E+004"
      Console.WriteLine("F: {0}", _
              floating.ToString("F04", ci))         ' Displays "F: 10761.9376"         
      Console.WriteLine("G: {0}", _ 
              floating.ToString("G", ci))           ' Displays "G: 10761.937554"
      Console.WriteLine("N: {0}", _
              floating.ToString("N03", ci))         ' Displays "N: 10,761.938"
      Console.WriteLine("P: {0}", _
              (floating/10000).ToString("P02", ci)) ' Displays "P: 107.62 %"
      Console.WriteLine("R: {0}", _
              floating.ToString("R", ci))           ' Displays "R: 10761.937554"            
      Console.WriteLine()
      
      ' Output integral values
      Dim integral As Integer = 8395
      Console.WriteLine("C: {0}", _
              integral.ToString("C", ci))           ' Displays "C: $8,395.00"
      Console.WriteLine("D: {0}", _
              integral.ToString("D6"))              ' Displays "D: 008395" 
      Console.WriteLine("E: {0}", _
              integral.ToString("E03", ci))         ' Displays "E: 8.395E+003"
      Console.WriteLine("F: {0}", _
              integral.ToString("F01", ci))         ' Displays "F: 8395.0"    
      Console.WriteLine("G: {0}", _ 
              integral.ToString("G", ci))           ' Displays "G: 8395"
      Console.WriteLine("N: {0}", _
              integral.ToString("N01", ci))         ' Displays "N: 8,395.0"
      Console.WriteLine("P: {0}", _
              (integral/10000).ToString("P02", ci)) ' Displays "P: 83.95 %"
      Console.WriteLine("X: 0x{0}", _
              integral.ToString("X", ci))           ' Displays "X: 0x20CB"
      Console.WriteLine()
   End Sub
End Module

请参阅See also