c# - 小数未正确舍入

标签 c# decimal rounding-error

我有一个名为“sum”的小数,其值为 5824088.999120m,但是当我尝试将其四舍五入到 3 位小数时,我得到的是 5824088.998m 而不是 >5824088.999m。它递减而不是留下 5824088.999m

这是为什么呢?这是我的代码:

List<decimal> quantityList = QuantityList();
List<decimal> priceList = PriceList();

decimal destination = 5824088.999M;
decimal sum = 0M;
bool lifesaver = false;

for (int x = 0; x < priceList.Count; x++)
{
    sum = 0M;
    for (int i = 0; i < 3500; i++)
    {
        priceList[x] += 0.001M;
        sum = 0M;
        for (int y = 0; y < priceList.Count; y++)
        {
            decimal multipleProduct = priceList[y] * quantityList[y];
            sum = sum + multipleProduct;
            Console.WriteLine(priceList[y] + " " + quantityList[y]);

            sum = Math.Round(sum, 3);
            Console.WriteLine("Sum: " + sum);
            Console.ReadKey();
            Console.WriteLine();
        }

        if (sum == destination)
        {
            Console.WriteLine("The new number is " + priceList[x] + " and it is the {0} element!", x);
            lifesaver = true;
            break;
        }
        else if (sum > destination)
        {
            Console.WriteLine("Limit exceeded!");
        }

        if (i == 3499)
        {
            priceList[x] -= 3.500M;
        }
        if (lifesaver == true)
        {
            break;
        }
    }//Second for loop

    if (lifesaver == true)
    {
        break;
    }
}//Main for loop

列表采用另一种方法。

最佳答案

您似乎有舍入错误累积,因此总数是错误的:

  for (int y = 0; y < priceList.Count; y++) {
    ...
    sum = Math.Round(sum, 3); // <- this accumulates round up errors
    ...
  }

假设 priceList 包含

  priceList = new List<Decimal>() {
    1.0004M, 1.0004M, 1.0004M};

quantityList全为1; 总和将为

1.000M, 2.000M, 3.000M

而实际总数为

Math.Round(1.0004M + 1.0004M + 1.0004M, 3) 

3.001M。 可能的补救措施是不提前四舍五入:

   for (int y = 0; y < priceList.Count; y++) {
      ...
      //DONE: comment out this: no premature rounding (within the loop)
      // sum = Math.Round(sum, 3);
      //DONE: but format out when printing out
      Console.WriteLine("Sum: {0:F3}", sum);
      ...
   } 

   // round up (if you want) after the loop
   sum = Math.Round(sum, 3);

关于c# - 小数未正确舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37068481/

相关文章:

C# NewtonSoft JsonConvert serializexmlnode 到嵌套数组?

c# - 当我在单独的线程上将随机数添加到列表框时,UI 卡住

c# - 如何在异步套接字中接收完整的屏幕截图?

c# - 无法在 javascript 中获取 html 文本框的值

c# - 如何操作整数值的特定数字?

java - for循环输入整数和小数

c# - 在 C# 中将 float 转换为十进制。为什么 (decimal)0.1F == 0.1M 不是因为四舍五入而为假?

javascript - 为什么 6.53 + 8 = 14.530000000000001 在 JavaScript 中?

php - 在 MySQL 中将 HEX 列转换为 DEC

Java 做数学不符合预期