如何在 if 条件下应用 == 十进制值?

How to apply == decimal value in if condition?

这是我一直试图执行的逻辑,但它给出了问题:

protected void Price_Update_Click(object sender, EventArgs e)
{
    decimal Price;   
    var gvr   = (GridViewRow)(sender as Control).Parent.Parent;
    int index = gvr.RowIndex;
    var box1  = (TextBox)GridView1.Rows[index].Cells[4].FindControl("TextBox1");
    bool prc  = decimal.TryParse(box1.Text, out Price);
    var PriceString = GridView1.Rows[index].Cells[4].Text.Replace(" AUD", "");

    var btn = (Button)sender;
    var row = (GridViewRow)btn.NamingContainer;
    var ProductNo = row.Cells[0].Text;
    var BranchNo  = row.Cells[6].Text;

    if (Price > 00.00)
    {
        var CS  = "data source=LAPTOP-ODS96MIK\MSSQL2014; database = Grocery_Demo; integrated security=SSPI";
        var con = new SqlConnection(CS);
        var cmd = new SqlCommand("UpdateProductQuantity", con);

        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        con.Open();
        cmd.Parameters.AddWithValue("@ProductPrice", Price);
        cmd.Parameters.AddWithValue("@ProductNo", ProductNo);
        cmd.Parameters.AddWithValue("@GroceryBranchNo", BranchNo);
        cmd.ExecuteNonQuery();
        con.Close();

        MessageBox("Price has been updated");
        DisplayProducts();
    }
    else if (Price == 00.00 || prc == false)
    {
        Label5.Text = "Please don't keep the price blank";
        DisplayProducts();
    }
}

我面临的问题是在两个 if 条件下都有红线,它表示:

Operator '>' cannot be applied to operands of type 'decimal' and 'double'

我还是想不通我漏掉的技巧在哪里。

如果提供适当的语法解决方案将会很有帮助。

总之,你不能用==来比较doubledecimal造成的错误。

Console.WriteLine((00.00).GetType()); // type is double

我们可以看到00.00的类型是double,但是你的Price值是decimal的类型,所以不能比较。

您需要在数字末尾添加或 M,因为 00.00 表示该值为 doublem可以让它变成十进制。

decimal

If you want a numeric real literal to be treated as decimal, use the suffix m or M

if (Price > 00.00m)