2014-05-09 31 views
-2

我正在创建POS(销售点),并且在尝试将价格“0.60”转换为整数时遇到问题。在C#中将包含句点(。)的字符串转换为Int32时的问题

数据背景:数据源的所有数据都来自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

+1

0.60不是整数... –

+0

一个整数,不能包含小数点,你应该转换为浮动或十进制 –

+0

@TMcKeown我知道这不是一个整数。有没有合理的方法来解决这个问题?你可以用Float或Decimal做一个例子吗?先谢谢了。 –

回答

3

0.60不是整数,错误是正确的

替代方案:

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

甚至更​​好:

Decimal d; 
if (decimal.TryParse(txtPrice.Text, out d) == false){ 
    //handle bad number... 
} 
+0

这是一个很好的答案,但用Decimal.TryParse()可能会更好。 –

+0

谢谢,建议采取。 –

+1

谢谢你,我刚刚使用了Decimal d,就像你说的那样,它工作。现在我将按照Rick Davin的说法和Yuval Itzchakov的验证原因添加TryParse()。 –

1

您需要使用decimal.ParseConvert.ToDecimal作为字符串显然不是int。在处理货币时推荐使用小数。

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

另外,我建议你看看TryParse要用于验证:

decimal price; 
if (decimal.TryParse(NewPrice, out price)) 
{ // do stuff } 
+0

处理货币时应该避免两次? –

+0

如果您正在处理货币,请使用'decimal'。更新了我的答案 –

0
Price = Convert.ToInt32(string.Format("{0.00}",txtPrice.Text)); 
在你从一个小数样式的格式转换为整数上面的代码

。 int32类型只能包含整数,因此convert方法会给你一个错误。相反,您可以使用double类型来正确保存您的值。

double Price; 
Price = Convert.ToDouble(string.Format("{0.00}",txtPrice.Text)); 
1

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

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

//Expected output: x = 1 
相关问题