错误十进制到整数,简单操作 C# 中的错误圆

Error Decimal to Int, bad round in simple operation C#

在 C# 中,我正在创建一个简单的指令,用于获取折扣后的价格。 我需要显示像 int 这样的值(从十进制舍入到 int),但是当我显示结果时,我可以看到像 47.5 -> 48 这样的舍入,但是 66.5 到 66...为什么 c# 舍入 +0.5 和 -0.5另一个呢?

using System;
using System.Collections.Generic;
                
public class Program
{
   public static void Main()
  {
    int discount = 5;
    
    Dictionary<string, int> coffee = new Dictionary<string, int>();
    
    coffee.Add("Americano", 50);
    coffee.Add("Latte", 70);
    
    int amount =0;
    decimal percentDiscount = (1- (decimal)(discount)/100);
    foreach(string key in coffee.Keys){
        Console.WriteLine((coffee[key] * percentDiscount));
        amount = Convert.ToInt32((coffee[key] * percentDiscount));
        Console.WriteLine(key+": "+amount);
    }
  }
}
//47.50
//Americano: 48
//66.50
//Latte: 66

如果您将鼠标悬停在 IDE 中的该方法上,您将看到以下文档。

value, rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

根据文档,数字始终四舍五入为偶数。

如果要将数字四舍五入,在将数字转换为整数之前,应使用小数 Round 方法并将 MidpointRounding 设置为 AwayFromZero

decimal.Round(coffee[key] * percentDiscount, 0, MidpointRounding.AwayFromZero)