-2

我正在创建一个 POS(销售点),但在尝试将价格“ 0.60”转换为整数时遇到了问题。

数据背景:数据源的所有数据都来自我已经设置并连接没有问题的 MySQL 数据库。

价格存储在一个文本框中并被格式化为“ 0.60”,我相信这就是它没有被转换的原因。我不断收到下面的消息。

附加信息:输入字符串的格式不正确。

        //Puts the Price Into a String.
        string NewPrice = txtPrice.Text;

        //Converts The Quantity In the TextBox field to a numbers.
        Quantity = Convert.ToInt32(txtQuant.Text);

        //Incorrect Format & Attempt One.
        //Price = Convert.ToInt32(NewPrice); <--- Problem.
        //Price = int.Parse(NewPrice);

        // I've also tried this method below with two '0' inside the { } brackets.
        // But Still No Luck.
        Price = Convert.ToInt32(string.Format("{0.00}",txtPrice.Text)); // <--- Problem.

        // Times Price & Quantity to get Total Price (0.60 * 2 = 1.20)
        TotalSingleItemPrice = Price * Quantity;

        // The Single Item Price is added into the overall total.
        TotalPrice += TotalSingleItemPrice;

        // Converts Total Item Price to String from Int.
        string TotalPriceStr = Convert.ToString(TotalSingleItemPrice);           

        // Puts TextBoxes / Strings Into One String array (I think).
        string[] InizialItemList = new string[] { cmboInitItem.Text, Convert.ToString(Price), Convert.ToString(Quantity), TotalPriceStr};

        // Adds The String Array Into the Data Grid View.
        DGVIIL.Rows.Add(InizialItemList);

我试图使用string.Format("{0.00}",txtPrice.Text)设置来解决这个问题,我只是看不到我看过的东西。我希望价格尽可能出现在我的 DataGridView - DGVIIL 中0.60

4

4 回答 4

3

0.60不是整数,错误就在

备择方案:

Decimal d = Decimal.Parse(txtPrice.Text);

甚至更好:

Decimal d;
if ( decimal.TryParse(txtPrice.Text, out d) == false ){
  //handle bad number...
}
于 2014-05-09T19:03:13.433 回答
1

您需要使用decimal.ParseorConvert.ToDecimal因为您的字符串显然不是int. 处理货币时建议使用小数。

Price = Convert.ToDecimal(NewPrice);
Price = decimal.Parse(NewPrice);

另外,我建议您考虑TryParse用于验证:

decimal price;
if (decimal.TryParse(NewPrice, out price))
{ // do stuff }
于 2014-05-09T19:05:27.400 回答
1

您需要将其转换为 double,然后再转换为 int。

int x = Convert.ToInt32( Convert.ToDouble("1.11")); 

//Expected output: x = 1
于 2014-05-26T07:37:55.137 回答
0
Price = Convert.ToInt32(string.Format("{0.00}",txtPrice.Text));

在上面的代码中,您正在从十进制样式格式转换为整数。int32 类型只能包含整数,因此 convert 方法会给你一个错误。相反,您可以使用双精度类型来正确保存您的值。

double Price;
Price = Convert.ToDouble(string.Format("{0.00}",txtPrice.Text));
于 2014-05-09T19:07:01.240 回答