C # Check whether the string is a number

Source: Internet
Author: User
C # Check whether the string is a number

This log is composed
Samool
Posted on AM

Regular Expression
String RegEx = @ ^ \ D + $;

Write a method by yourself: This is what I wrote.
Private bool isnumber (string S)
{
Int flag = 0;
Char [] STR = S. tochararray ();
For (INT I = 0; I <Str. length; I ++)
{
If (char. isnumber (STR [I])
{
Flag ++;
}
Else
{
Flag =-1;
Break;
}
}
If (flag> 0)
{
Return true;
}
Else
{
Return false;
}
}

Test
Private void button#click (Object sender, system. eventargs E)
{
If (isnumber (textbox1.text. Trim ()))
{
Textbox2.text = is a number;
}
Else
{
Textbox2.text = not a number;
}
}

 

Try
{
Double. parse (this. textbox1.text );
Response. Write (number );
}
Catch
{
Response. Write (not a number );
}

You can also use a regular expression:
Using system. Text. regularexpressions;
------------------------
RegEx r = new RegEx (@ ^ \ D + (\.)? \ D * $ );
If (R. ismatch (this. textbox1.text ))
{
This. response. Write (a number );
}
Else
{
This. response. Write (not a number );
}

Public static bool strisint (string Str)
{
Try
{
Int32.parse (STR );
Return true;
}
Catch
{
Bool flag = false;
Return flag;
}
}

 

Regular expressions should be used:
String Pattern = @ ^ \ D + (\. \ D )? $;
If (text1.text. Trim ()! =)
{
If (! RegEx. ismatch (sign_money.text.trim (), pattern ))
{
Text1 is not a number;
}
Else
{
Text1 is a number;
}
}

Original article link

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.