2014-10-18 22 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