的C#程序接收標籤的字符串:將文本轉換爲整數比較C#
1.2345 V
我需要使用<或>這個值在一個「如果」語句進行比較。 如何將上述字符串轉換爲整數? 我試着使用:
int anInteger;
anInteger = Convert.ToInt32(textBox1.Text);
anInteger = int.Parse(textBox1.Text);
但它引發錯誤System.FormatException: incorrect format
。
的C#程序接收標籤的字符串:將文本轉換爲整數比較C#
1.2345 V
我需要使用<或>這個值在一個「如果」語句進行比較。 如何將上述字符串轉換爲整數? 我試着使用:
int anInteger;
anInteger = Convert.ToInt32(textBox1.Text);
anInteger = int.Parse(textBox1.Text);
但它引發錯誤System.FormatException: incorrect format
。
您必須刪除V
末和使用decimal.Parse
/TryParse
:
decimal d;
bool validFormat = decimal.TryParse(textBox1.Text.TrimEnd('V', ' '), out d);
在我的國家,它使用,
爲十進制和.
作爲組分隔符這會產生12345
。
如果你不是要忽略任何不是字符串中的某個數字:
int number = int.Parse(new string(textBox1.Text.Where(char.IsDigit).ToArray()));
在C#7中,你可以做'出小數點d',保存一點的空間:) – Jaxi
,你可能不得不使用不變的文化取決於提問者的位置 –
@YairHalberstadt:好吧,它適用於我,我不使用'.'作爲小數點分隔符。結果是'12345'這有點奇怪 –
如果你堅持整數(點在1.2345
768,16是忽略和最終的結果是12345
):
// Any digits (including, say, Persian ones) are OK
int anInteger = (textBox1.Text
.Where(c => char.IsDigit(c))
.Aggregate(0, (s, a) => s * 10 + (int)char.GetNumericValue(a));
或者
// Only '0'..'9' digits supported
int anInteger = (textBox1.Text
.Where(c => c >= '0' && c <= '9')
.Aggregate(0, (s, a) => s * 10 + a - '0');
另請注意,取決於您當前的文化設置,您可以獲得不同的結果。
下面的代碼與去DE培養,運行設置
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de-DE");
string str = "1.23";
decimal val = decimal.Parse(str);
val.Dump(); // output 123
string str2 = "1,23";
decimal val2 = decimal.Parse(str2);
val2.Dump(); // output 1,23
下面的代碼與EN-US區域性已運行設置
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
string str = "1.23";
decimal val = decimal.Parse(str);
val.Dump(); // output 1.23
string str2 = "1,23";
decimal val2 = decimal.Parse(str2);
val2.Dump(); // output 123
請使用LINQPad來運行代碼。
你可以嘗試 -
decimal dec=2;
string str = "3.23456";
dec = Convert.ToDecimal(str.ToString());
int a = Convert.ToInt32(dec);
這是_not_一個整數,但雙/十進制值。在解析之前,你還必須提取'V' –
你期望在1.2345 V之外得到什麼樣的整數值? – Rahul
您只想要數字還是'V'具有特殊含義,因爲該字符串不能轉換爲數字值。 – Jerodev