在某些情况下,C# 十进制乘法会导致尾随 0。为什么会发生这种情况,如何删除尾随的 0?

C# decimal multiplication results in trailing 0 in some cases. Why does this happen and how do I remove this trailing 0?

当我将两个 decimal 数字相乘时,出于某种原因,数字末尾有一个尾随 0。如果两个 decimal 数字的最后一位的乘积是 10 的倍数,就会发生这种情况。

这里有 2 个例子:

decimal a = 0.4M;
decimal b = 1.05M;
Console.WriteLine(a * b); // 0.420

decimal c = 0.06M;
decimal d = 1.15M;
Console.WriteLine(c * d); // 0.0690

为什么会这样?有没有办法从 decimal?

中删除尾随的 0

我想要的结果是 0.42 / 0.069 而不是 0.420 / 0.0690 作为 decimal.

C# 小数不仅仅存储值,它们存储关于精度的信息。您可以使用如下代码看到:

decimal d1 = 0M;
decimal d2 = 0.00M;
 
Console.WriteLine(d1);  // 0
Console.WriteLine(d2);  // 0.00

这个精度可以在乘法或除法时改变:

decimal d1 = 10M;
decimal d2 = 10.00M;
decimal d3 = 5.0M;
 
Console.WriteLine(d1 * d3); // 50.0
Console.WriteLine(d2 * d3); // 50.000

如果您不想使用默认的输出格式,则需要使用特定的输出格式,例如 d3.ToString("0.#####"),它将包含小数点后最多五位有效数字。

下面的完整程序显示了上述所有效果,以及一种执行特定格式的方法(最后几行显示了如何在货币等内容的小数点后获得固定位置):

using System;
                    
public class Program {
  public static void Main() {
    decimal d1 = 0M;
    decimal d2 = 0.00M;
    Console.WriteLine(d1); // 0
    Console.WriteLine(d2); // 0.00

    d1 = 7M;
    d2 = 10.00M;
    decimal d3 = 5.0M;
    Console.WriteLine(d1 * d3); // 35.0
    Console.WriteLine(d2 * d3); // 50.000

    d1 = 1234567.89000M;
    Console.WriteLine(d1);                     // 1234567.89000
    Console.WriteLine(d1.ToString("0.#####")); // 1234567.89

    Console.WriteLine(d2 * d3);                  // 50.000 (see above)
    Console.WriteLine((d2 * d3).ToString("F3")); // 50.00
  }
}