Several methods to verify whether the input is Numeric

Source: Internet
Author: User

Method 1:

 

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;
}

 

Method 2:

Private bool isnumeric (string S)
{
Char ch0 = '0 ';
Char ch9 = '9 ';
For (INT I = 0; I <S. length; I ++)
{
If (S [I] <ch0 | s [I]> ch9 ))
{
This. lblwarning. Text = "here we should enter an integer and it is not negative! ";
Return false;
}
}
Return true;
}

 

Method 3:

Static bool isnumeric (string Str)
{
System. Text. regularexpressions. RegEx reg1
= New system. Text. regularexpressions. RegEx (@ "^ [-]? \ D + [.]? \ D * $ ");
Return reg1.ismatch (STR );
}

 

Method 4: (Scalable)

Public static bool isconvert (string expression, type datatype)
{
Switch (datatype. Name)
{
Case "double ":
Try
{
Double. parse (expression );
Return true;
}
Catch
{
Return false;
}
Case "datetime ":
Try
{
Datetime. parse (expression );
Return true;
}
Catch
{
Return false;
}
Default:
Return true;
}
}

The regular expression is written as follows:

Static bool isnumeric (string Str)
{
System. Text. regularexpressions. RegEx reg1
= New system. Text. regularexpressions. RegEx (@ "^ [-]? \ D + [.]? \ D * $ ");
Return reg1.ismatch (STR );
}

 

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.