?
Solved

How to Determine if String is an Integer Using C#

Posted on 2012-04-03
11
Medium Priority
?
548 Views
Last Modified: 2012-04-09
I am having locating information on how to determine if a string is an integer in C#. Are there any built in functions that could look at this and deterine if the string is a integer? Any help would be greatly appreciated.
0
Comment
Question by:thenthorn1010
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
  • +3
11 Comments
 
LVL 12

Accepted Solution

by:
Alfredo Luis Torres Serrano earned 400 total points
ID: 37803101
Try the static IsNumber() method on the Char class.

E.g.:

char c = 'a';
if (Char.IsNumber(c))
{
//do whatever...
}

Hope that helps.
0
 
LVL 9

Assisted Solution

by:wasiftoor
wasiftoor earned 400 total points
ID: 37803102
You are use the built in parse functions for this purpose. Sample code attached.

string Str = textBox1.Text.Trim();
double Num;
bool isNum = double.TryParse(Str, out Num);
if (isNum)
MessageBox.Show(Num.ToString());
else
MessageBox.Show("Invalid number");

Open in new window

0
 
LVL 5

Assisted Solution

by:hafeezmca
hafeezmca earned 400 total points
ID: 37803143
Hi,

Place a textbox, command button and label.
Place the following code to acheive the task.

protected void Button1_Click(object sender, System.EventArgs e)
{
      bool result = false;
      result = IsInt(this.TextBox1.Text);
      if (result == true) {
            this.Label1.Text = "Integer";
      } else {
            this.Label1.Text = "Non Integer";
      }

}

private bool IsInt(string param)
{
      try {
            int i = int.Parse(param);
            return true;
      } catch {
            return false;
      }
}

There are other ways you could do this as well like making sure that the only numeric characters are entered in the texbox by using Range validator control. This will wont require you to write a single line of code. It can be done at design time itself.
0
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

 
LVL 27

Expert Comment

by:Chinmay Patel
ID: 37804440
Hi thenthorn1010,

I would use wasiftoor's solution.

It's always good to use TryParse methods, just don't use double.TryParse. use int.TryParse.
Also this TryParse methods are available for many primitive data types.

Regards.
Chinmay,
0
 
LVL 15

Assisted Solution

by:Navneet
Navneet earned 400 total points
ID: 37804770
Hi!

Add reference to your Project
Microsoft.VisualBasic


using Microsoft.VisualBasic;

then in project try

Information.IsNumeric()


Thanks!
0
 
LVL 40

Assisted Solution

by:Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger) earned 400 total points
ID: 37804894
Chinmay_Patel answer is the only one that it really good. All the other ones have problems.

Char.IsNumber will say OK with numbers that are not integer.
Same with Double.TryParse.
Same thing with Information.IsNumeric, that is VB anyway. Why use VB in C# when the framework has methods to do the job?
int.Parse imply a try...catch, while TryParse does the job without a try...catch, which is always better because triggering exceptions requires a lot of resources.

So the only way to get a good result without involving too much overhead is to use int.TryParse.
0
 
LVL 15

Expert Comment

by:Navneet
ID: 37805279
@JamesBurger

Once code is compiled nothing is VB.Net or C#, Everything is .Net(MSIL).
Also IsNumeric is tried and tested.
When things are available, why re-invent the wheel.

Also which has beter chances of success?

            int res = 0;
            int.TryParse("2147483648",out res);
            bool isNum = Information.IsNumeric("2147483648");

Ofcourse I may be wrong saying IsNumeric is good.

Thanks!
0
 
LVL 15

Expert Comment

by:Navneet
ID: 37805281
0
 
LVL 40
ID: 37806478
@navneethedge

Look at the date of the article you are pointing: 2003, 9 years ago, that is a long time. And it was at the beginning of the year, we were still in Visual Studio 2002, with framework 1.0. Things have change a bit since then. TryParse did not exist at that time.

TryParse is part of the framework and available in all languages. IsNumeric forces you to reference a library from another language to work in C#, a very strange idea considering that C# has what you need.

And the main problem with the question discussed here is that it is about knowing if a string is an integer. If a string contains "1.2", IsNumeric will return True while the string does not contain an integer. Bad answer.

TryParse adapt to any type you use it with. If you call it on a Byte for instance, it won't return True on negative values or if the value in the String is higher than 255. It is a lot more precise. If you were to use IsNumeric, you would have to check for those 2 conditions. IsNumeric does it in one shot.
0
 
LVL 15

Expert Comment

by:Navneet
ID: 37806721
@JamesBurger : thanks and agree.
0
 
LVL 27

Expert Comment

by:Chinmay Patel
ID: 37808067
@jamesburger
:P Thanks :) Saved Me Some Time ;)
0

Featured Post

PowerShell Core for Advanced Linux Administrators

Understand advanced principals around Powershell Core with a focus on the Linux Administrator.  This course covers how to administer numerous environments across multiple platforms including Linux, Azure, AWS, and Google Cloud from a single shell instance.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question