C# 为什么我的输出要舍入十进制数?我应该用十进制还是别的?

C# 为什么我的输出要舍入十进制数?我应该用十进制还是别的?,c#,wpf,floating-point,double,decimal,C#,Wpf,Floating Point,Double,Decimal,这里是业余爱好者 我正在创建一个基本的“报价计算器”,ItemQuantity*ItemCost。 我希望数量是整数(1,2,3,4,5等),成本可以是整数,也可以有小数位(1,2,3.45,6.2) 在我的WPF应用程序中一切正常,但是,我用来输出itemQuantity*itemCost之和的TextBlock显示了一个四舍五入的整数 显然,我希望它精确到小数点后两位,但目前它将数字四舍五入。我做错了什么 List<Items> quoteList = new List<I

这里是业余爱好者

我正在创建一个基本的“报价计算器”,ItemQuantity*ItemCost。 我希望数量是整数(1,2,3,4,5等),成本可以是整数,也可以有小数位(1,2,3.45,6.2)

在我的WPF应用程序中一切正常,但是,我用来输出
itemQuantity*itemCost
之和的TextBlock显示了一个四舍五入的整数

显然,我希望它精确到小数点后两位,但目前它将数字四舍五入。我做错了什么

List<Items> quoteList = new List<Items>();

 public void button_itemadd_Click(object sender, RoutedEventArgs e)
    {
        quoteList.Add(new Items()
        {
            itemName = input_itemdesc.Text,
            itemQuantity = Convert.ToInt32(input_itemquantity.Text),
            itemCost = Convert.ToDecimal(input_itemcost.Text)

        });

        dataGridView1.ItemsSource = "";
        dataGridView1.ItemsSource = quoteList;
        updateQuote();
    }

    public void updateQuote()
    {
        decimal costTotal = 0;

            for (int i = 0; i < quoteList.Count; i++)
        {
            costTotal += (Convert.ToInt32(quoteList[i].itemCost) * Convert.ToDecimal(quoteList[i].itemQuantity));
        }
// output_quotecost is the TextBlock
        output_quotecost.Text = costTotal.ToString();
    }
}


class Items
{
    public string itemName { get; set; }
    public int itemQuantity { get; set; }
    public decimal itemCost { get; set; }
}
List quoteList=new List();
公共无效按钮\u项目添加\u单击(对象发送者,路由目标)
{
quoteList.Add(新项目()
{
itemName=input_itemdesc.Text,
itemQuantity=Convert.ToInt32(输入_itemQuantity.Text),
itemCost=Convert.ToDecimal(输入\u itemCost.Text)
});
dataGridView1.ItemsSource=“”;
dataGridView1.ItemsSource=quoteList;
updatekote();
}
公共void updatekote()
{
十进制成本总计=0;
对于(int i=0;i

看起来您在以下位置混淆了转换方法:

costTotal += (Convert.ToInt32(quoteList[i].itemCost) *
              Convert.ToDecimal(quoteList[i].itemQuantity));
相反,它应该是:

costTotal += (Convert.ToDecimal(quoteList[i].itemCost) *
              Convert.ToInt32(quoteList[i].itemQuantity));

您必须将
.ToInt32
替换为
.todeciml
,才能获得正确的输出。

看起来您混淆了以下转换方法:

costTotal += (Convert.ToInt32(quoteList[i].itemCost) *
              Convert.ToDecimal(quoteList[i].itemQuantity));
相反,它应该是:

costTotal += (Convert.ToDecimal(quoteList[i].itemCost) *
              Convert.ToInt32(quoteList[i].itemQuantity));
必须将
.ToInt32
替换为
.todeciml
,才能获得正确的输出