Skip to main content
 首页 » 编程设计

c#之Convert.ToString(Decimal, IFormatProvider) 或 String.Format

2024年02月13日8傻小

我已经看到问题 Odd decimal type behavior for ToString(IFormatProvider)

这是我的测试代码

// Define an array of numbers to display. 
double[] numbers = { -1.5345e16, -123.4321, 19092.123, 1.1734231911290e16 }; 
// Define the culture names used to display them. 
string[] cultureNames = { "en-US", "fr-FR", "ja-JP", "ru-RU" }; 
 
foreach (double number in numbers) 
{ 
    Console.WriteLine("{0}:", Convert.ToString(number, 
                              System.Globalization.CultureInfo.InvariantCulture)); 
    foreach (string cultureName in cultureNames) 
    { 
        System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(cultureName); 
        culture.NumberFormat.NumberGroupSizes = new int[] {2,2,3}; 
        culture.NumberFormat.NumberDecimalDigits = 5; 
        Console.WriteLine(".ToString          {0}: {1,20}", 
                          culture.Name, number.ToString("N", culture)); 
        Console.WriteLine("Convert.ToString   {0}: {1,20}",  
            culture.Name, Convert.ToString(number, culture)); 
    } 
    Console.WriteLine(); 
} 

示例结果如下:

为什么 Convert.ToString 没有应用格式?

这是用 Win7 Prof/VS2010+SP1Rel (10.0.40219.1)

请您参考如下方法:

根据 Convert.ToString(double, IFormatProvider) 的文档:

This implementation is identical to Double.ToString(IFormatProvider)

... 然后是 documented作为:

The ToString(IFormatProvider) method formats a Double value in the default ("G", or general) format of a specified culture.

当您调用 ToString 时,您将传入 N - 如果您传入 G,您将获得相同的结果作为 Convert.ToString。

G format specifier documentation状态:

The result string is affected by the formatting information of the current NumberFormatInfo object. The following table lists the NumberFormatInfo properties that control the formatting of the result string.

... 并列出 NegativeSign、NumberDecimalSeparator、PositiveSign。您的代码没有设置任何这些属性,这就是为什么它没有任何区别。如果你写:

culture.NumberFormat.NumberDecimalSeparator = "#" 

例如,将影响Convert.ToString的输出。