我需要檢查一個字符串是否只包含數字。我怎麼能在C#中實現這一點?僅檢查字符串和一個可選的小數點。
string s = "123" → valid
string s = "123.67" → valid
string s = "123F" → invalid
是否有像IsNumeric這樣的函數?
我需要檢查一個字符串是否只包含數字。我怎麼能在C#中實現這一點?僅檢查字符串和一個可選的小數點。
string s = "123" → valid
string s = "123.67" → valid
string s = "123F" → invalid
是否有像IsNumeric這樣的函數?
double n;
if (Double.TryParse("128337.812738", out n)) {
// ok
}
作品假設數量不溢出雙
一個巨大的字符串,嘗試正則表達式:
if (Regex.Match(str, @"^[0-9]+(\.[0-9]+)?$")) {
// ok
}
添加在科學記數法(E/E)或+/-跡象,如果需要...
我認爲你可以使用正則表達式,在正則表達式類
Regex.IsMatch(yourStr,「\ d」)
或類似的東西在我頭頂。
或者你可以使用Parse方法int.Parse(...)
這應該工作:
bool isNum = Integer.TryParse(Str, out Num);
Int.TryParse將在他的第三個「123.67」測試用例上失敗 – ZombieSheep 2010-01-19 09:43:50
您可以使用double.TryParse
string value;
double number;
if (Double.TryParse(value, out number))
Console.WriteLine("valid");
else
Console.WriteLine("invalid");
從MSDN採取的措施(如何通過使用Visual C#實現Visual Basic .NET IsNumeric功能):
// IsNumeric Function
static bool IsNumeric(object Expression)
{
// Variable to collect the Return value of the TryParse method.
bool isNum;
// Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero.
double retNum;
// The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent.
// The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned.
isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
}
如果您收到的字符串作爲一個參數更靈活的方式是使用正則表達式,如其他文章中所述。 如果您從用戶那裏獲得輸入,您可以掛鉤KeyDown事件並忽略所有不是數字的鍵。這樣你就可以確定你只有數字。
如前所述上面如果你不喜歡這樣(出於某種原因),您可以使用double.tryParse
,您可以編寫自己的擴展方法:
public static class ExtensionMethods
{
public static bool isNumeric (this string str)
{
for (int i = 0; i < str.Length; i++)
{
if ((str[i] == '.') || (str[i] == ',')) continue; //Decide what is valid, decimal point or decimal coma
if ((str[i] < '0') || (str[i] > '9')) return false;
}
return true;
}
}
用法:
string mystring = "123456abcd123";
if (mystring.isNumeric()) MessageBox.Show("The input string is a number.");
else MessageBox.Show("The input string is not a number.");
輸入:
1234 56abcd123
123。6
輸出:
假
真正
應該用什麼參數? 它會接受一個巨大的字符串?有什麼限制嗎? – Maneesh 2010-01-19 09:41:20
對於一個巨大的字符串,你需要一個正則表達式 – jspcal 2010-01-19 09:43:07
感謝reg Exp解決方案!謝謝jspcal – Maneesh 2010-01-19 10:07:24