.Net - 一般数字格式似乎不保留零

.Net - General numeric formatting does not seem to preserve zeros

正在查看 the documentation on Standard Numeric Format Strings。它说

However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved.

对我来说,尾随零的定义只是指数字末尾的任何零,无论它们是在小数点之前还是之后。

因此,根据我对尾随零的理解,300 和 3.00 都有 2 个尾随零。

但是,实际试了一下,好像只保留了小数点前的尾随零。

我只是误解了这里尾随零的定义,还是会保留小数点后的零?

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(new Decimal(10.000).ToString("G"));
        Console.WriteLine(new Decimal(0.000000).ToString("G"));
        Console.WriteLine(new Decimal(30000).ToString("G"));
    }
}

参见示例: https://dotnetfiddle.net/O2GwOY

问题是您没有将数字指定为 decimal 而是 double 文字。 由于 double 不保留尾随零,因此构造函数看不到它们。对于前两个示例,您使用的是构造函数

public Decimal (double value)

最后一个

public Decimal (int value)

尝试:

Console.WriteLine(10.000m.ToString("G"));
Console.WriteLine(0.000000m.ToString("G"));
Console.WriteLine(30000m.ToString("G"));

m 类型后缀("m" 表示金钱)指定了一个 decimal 数字。这按预期工作。

这也有效:

Convert.ToDecimal("10.0000").ToString("G")

Decimal.Parse("10.0000").ToString("G")

参见:Value types table (C# Reference)