为什么 C# 在格式化期间截断字符串精度?

Why does C# truncate string precision during Format?

给定一个字符串和一个等值的双精度值,string.Format 截断不同。

double x = 88.2;
string y = "88.2";
string output_1 = String.Format("{0:0.00}", x);
string output_2 = String.Format("{0:0.00}", y);

在这种情况下,output_1 将是“88.20”,output_2 将是“88.2”。

有没有办法不使用

Double double_var;
string output;
if (Double.TryParse(input, out double_var))
{
    output = String.Format("{0:0.00}", double_var);
}
else
{
    output = String.Format("{0:0.00}", input);
}

这是我为文件的记录集创建的通用文件生成器,我真的很想尽可能避免这种情况。

String.Format 不会将格式应用于字符串。您知道字符串包含数字,但 .NET 不包含。

所以是的,您必须将字符串解析为数字并格式化该数字。

来自MSDN: String.Format()

A number of types support format strings, including all numeric types (both standard and custom format strings), all dates and times (both standard and custom format strings) and time intervals (both standard and custom format strings), all enumeration types enumeration types, and GUIDs. You can also add support for format strings to your own types.

这不包括字符串。

为了让对象支持自定义格式字符串,它需要 implement IFormattable,上面提到的类型也是如此。

鉴于这些 类:

public class FormattableFoo : IFormattable 
{
    public string ToString(string format, IFormatProvider provider)
    {
        return $"FooFormat: '{format}'";
    }
}

public class Foo
{
    public override string ToString()
    {
        return "Foo";
    }
}

这些调用:

Console.WriteLine("{0:0.00}", new Foo());
Console.WriteLine("{0:0.00}", new FormattableFoo());

输出将是:

Foo
FooFormat: '0.00'

给定 System.String doesn't implement IFormattableFoo 也没有),其 ToString() 方法将在没有格式的情况下被调用。

另见 MSDN: Customizing Format Strings

string 没有实现 IFormattable 所以任何指定的格式化参数将被忽略。另一方面,double 可以解释提供的 0.00 格式说明符。

旁注:C# 6 有一个 FormattableString 但只是为了支持内插字符串中格式参数的不同区域性。