C # (isnumeric) Four Methods for converting a string to a number

Source: Internet
Author: User
Judge whether the string in C # Is a number. If it is converted to the int type

1. Use a regular expression (positive and negative values can be determined)
Public int isnumeric (string Str)
{
Int I;
If (STR! = NULL & system. Text. regularexpressions. RegEx. ismatch (STR, @ "^ -? \ D + $ "))
I = int. parse (STR );
Else
I =-1;
Return I;
}
2. Pass characters
/// <Summary>
/// Determine whether it is a number
/// </Summary>
/// <Param name = "Number"> </param>
/// <Returns> </returns>
Private bool isnumeric (string number)
{
Try
{

For (INT I = 0; I <number. length; I ++)
{
If (number [I] <'0' | Number [I]> '9 ')
{
Return false;
}
}
Return true;
}
Catch
{
Return false;
}
}
3. Use the char. isnumber Method
/// Determine whether it is a number
/// </Summary>
/// <Param name = "Number"> </param>
/// <Returns> </returns>
Private bool isnumeric (string number)
{
Try
{

For (INT I = 0; I <number. length; I ++)
{
If (! Char. isnumber (number, I ))
{
Return false;
}
}
Return true;
}
Catch
{
Return false;
}
}
4. Try and catch
/// Determine whether it is a number
/// </Summary>
/// <Param name = "Number"> </param>
/// <Returns> </returns>
Private bool isnumeric (string number)
{
Try
{
Int. parse (number );
Return true;
}
Catch
{
Return false;
}
}

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.