2014-10-18 138 views
-1

我正在从Excel文件读取表示价格的列。 (这些行在循环中)。C#:使用数字和文本将字符串转换为浮点数

dynamic tempPrice = (range.Cells[i, 15] as Excel.Range).Value2; 
float price = (tempPrice == null) ? 0 : (float)tempPrice; 

有三种可能的情况:

  • 细胞可能是空的(在这种情况下,我将其转换为0)
  • 细胞可能包含一个数字。
  • 单元格可能包含一个数字串和货币名称(例如“140 USD”,“140 $”等)。

在第三种情况下(这打破了我的代码),我怎样才能得到的数字,并将其转换为浮动?

+1

看看[这个问题](http://stackoverflow.com/questions/14162357/convert-currency-string-to-decimal) – qqbenq 2014-10-18 13:27:37

回答

2

您可以使用此代码

float.Parse(tempPrice , NumberStyles.AllowCurrencySymbol | NumberStyles.Number); 
+5

TryParse是一个更好的方法来使用。 – 2014-10-18 14:13:32

0

当您尝试解析值可以做到这一点

float price; 
if(!Single.TryParse(Regex.Replace(tempPrice, "\D+$", ""), out price)) { 
    price = 0; 
} 
// if it doesn't enter the condition, then price will have the parsed float value. 
1

,你应该总是验证在第一,如果它可以在解析之前进行解析。这样做,可以避免运行时出现任何类型的错误。

这里是你如何能做到这一点(你可以发现有一个类似的方式:https://social.msdn.microsoft.com/Forums/vstudio/en-US/701df7da-17d8-41b5-b2d2-94b2be9c0191/floattryparse

if(float.TryParse(tempPrice,NumberStyles.AllowCurrencySymbol, out value) 
    { 
    Console.WriteLine("Converted '{0}' to {1}.", tempPrice, value); 
    } 

希望它可以帮助你!

+0

如果提供的答案以任何方式帮助你,或者实际上你是在寻找,请将其标记为答案,以便其他人在将来知道! :) – 2014-10-19 00:55:36

+0

谢谢,这是最有帮助的,但“AllowCurrencySymbol”不能识别在这个特定的Excel文件中的所有情况(创建它的人有很多输入错误)。 – user3109098 2014-10-19 09:09:00

+0

尝试逻辑或并写入NumberStyle.Number。它至少应该在99%的情况下工作,至少我认为!让我知道它是否对你有帮助 – 2014-10-19 11:22:28