2012-06-06 30 views
0

我有以下的C#代碼是,在從一個數據表中的數據讀出(從Excel電子表格構建這是原始)如何可以解析在C#這個數據是從一個數據表來

private byte GetVal(DataRow dataRow, string caption) 
    { 
     var val = dataRow.GetValue(caption).ToString().Trim(); 
     if (!String.IsNullOrEmpty(val)) 
     { 
      return (byte)(Decimal.Parse(val) * 100); 
     } 
     return (byte)0; 
    } 

這是吹起來,因爲沒有的值:「5.5555555555555552E-2」從細胞中的一個(VAL變量)讀取

其在這條線吹起來:

return (byte)(Decimal.Parse(val) * 100); 

與錯誤:輸入字符串格式不正確。

解決此問題的最佳方法是什麼,以便我可以讀取值?

回答

2

試試這個:

return (byte)(Decimal.Parse(val, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture)); 

Decimal.Parse Method (String, NumberStyles, IFormatProvider)

NumberStyles.AllowExponentAllowExponentNumberStyles.Float一個子集)

Indicates that the numeric string can be in exponential notation. The AllowExponent flag allows the parsed string to contain an exponent that begins with the "E" or "e" character and that is followed by an optional positive or negative sign and an integer. In other words, it successfully parses strings in the form nnnExx, nnnE+xx, and nnnE-xx. It does not allow a decimal separator or sign in the significand or mantissa; to allow these elements in the string to be parsed, use the AllowDecimalPoint and AllowLeadingSign flags, or use a composite style that includes these individual flags.

+0

現在我得到的是同樣的錯誤時,數字是「0.5」。 。有什麼建議麼 ? – leora

+0

@Ieora。編輯我的答案,但爲什麼你認爲這是一個字節,當有小數位的值?然後我會建議返回'Decimal'或'Double'。 –

1
return (byte)(Decimal.Parse(val, NumberStyles.AllowExponent) * 100); 
+1

你的代碼存在語法問題;) –

+0

lol oops。謝謝。 – seekerOfKnowledge

相關問題