【问题标题】:My program is not saving numbers correctly我的程序没有正确保存数字
【发布时间】:2018-01-03 11:52:06
【问题描述】:

当我从文本框 (txtMaterialUnitPrice,txtMaterialUnitPrice) 输入十进制数字时,例如 4,5 和 6,5,总价格应该是 29,25,但它是 29。这是我的代码。

private void btnSale_Click(object sender, EventArgs e)
    {
        salesTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        materialPrice = Decimal.Parse(txtMaterialUnitPrice.Text);
        purchasedWeight = Decimal.Parse(txtMaterialUnitPrice.Text);
        totalPrice = materialPrice * purchasedWeight;

        curSales = Sales.Insert(customerID, customerNameSurname, customerPlate, materialID, materialType, materialPrice, purchasedWeight, totalPrice, salesTime, txtExplanation.Text);

        LoadAll();
    }

这是插入部分。

 public static Sales Insert(int cID, String cNameSurname, String cPlate, int mID, String mName, Decimal mPrice, Decimal pWeight, Decimal totalPrice, String dt, String explanation)
    {
        String query = string.Format("INSERT INTO sales(CustomerID,CustomerNameSurname,CustomerPlate,MaterialID,MaterialType,MaterialPrice,PurchasedWeight,TotalPrice,SalesDate,Explanation) VALUES ('{0}', '{1}' , '{2}', '{3}','{4}','{5}','{6}','{7}','{8}','{9}')", cID, cNameSurname, cPlate, mID, mName, mPrice, pWeight, cleanAmount, dt, explanation);

        MySqlCommand cmd = new MySqlCommand(query, DB.dbConn);

        DB.dbConn.Open();

        cmd.ExecuteNonQuery();

        int id = (int)cmd.LastInsertedId;

        Sales sale = new Sales(id, cID, cNameSurname, cPlate, mID, mName, mPrice, pWeight, totalPrice, dt, explanation);

        DB.dbConn.Close();

        return sale;
    }

【问题讨论】:

  • 不要使用字符串连接/格式化。改用参数
  • 可能是因为 29,25 会被视为 2 个值.. 29 和 25。更不用说也与您的代码相关的 sql 注入概念
  • materialPrice = Decimal.Parse(txtMaterialUnitPrice.Text); purchasedWeight = Decimal.Parse(txtMaterialUnitPrice.Text); 似乎是相同的文本框。是这个问题吗?
  • 正如@CamiloTerevinto 所说,使用参数来传递实际对象,而不是可能不是数据库预期格式的字符串表示。更不用说,因为里面有字符串,to avoid Bobby Tables.
  • 什么是“cleanAmount”?您正在为 TotalPrice 列插入该值。

标签: c# mysql database


【解决方案1】:

这可能有两个原因 1.您的表列“TotalPrice”是 INT 类型而不是 DECIMAL 或者 2.你的'Sales'对象类属性'TotalPrice'是整数或者不是不存储小数点的东西。

【讨论】:

  • 很抱歉,但没有一个是正确的。因为我的列是 DECIMAL(10,2) 类型,而且我的属性“TotalPrice”也是十进制的。
【解决方案2】:

您的解决方案中的问题是“,”符号。 C# 中的逗号十进制值使用“.”标志这就是它结合它的原因

//示例 //这会起作用

十进制测试 = 7.5;

//这行不通

十进制测试 = 7,5;

更改十进制指针符号

【讨论】:

  • 这个我已经试过了。它改变了这个数字并取为 75。@user1407955
  • 记住 parse 的语法:Decimal.TryParse(value, out number) 你要转换的值和你要在 out 参数中转换的值。
猜你喜欢
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多