C # method to verify whether the input is numeric

Source: Internet
Author: User
In fact, you can use regular expressions
static bool IsNumeric (String str)
{
if (Str==null | |) str. length==0)
return false;
foreach (char c in str)
{
if (! Char.isnumber (c))
{
return false;
}
}
return true;
}

Regular expressions are written in the following way:


static bool IsNumeric (String str)
{
System.Text.RegularExpressions.Regex REG1
= new System.Text.RegularExpressions.Regex (@ "^[-]?\d+[.")? \d*$ ");
Return REG1. IsMatch (str);
}


In fact, the most single is the function in vb.net, the following code snippet
Using Microsoft.VisualBasic

Information.isnumeric (Str_input)
Returns TRUE or FALSE to determine whether a number
However, it is necessary to add-lmicrosoft.visualbasic at compile time to compile successfully
CSDN Netizen (2005-11-24)
What if it's done directly?
try{
Float F=float.parse (temp);
}
catch (Exception ex)
{
MessageBox.Show ("This is not a number");
}
Dancefire (2005-11-13)
I think the regular expression is not correct, leading 0 in front of the decimal point should allow omitting, 0 after the decimal point, but also allow omitting, but do not allow separate decimal point. Your expression cannot satisfy a leading 0 omission. And, most importantly, "." Any character is represented in a regular expression, so for your expression, 2A2 can also pass the test.
^[-]?\d+[.]? \d*$

Should read as follows:
^[-]? (\d+\.?) \d*|\.\d+) $


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.