How to Check Value is Number or Not in C#.Net

How to validate value in a string is integer or decimal value using c#.net. By using TryParse we can validate or check string value is int or decimal.
In today's article I will show you a simple tutorial with an example how you can check a string value is a decimal or integer number or not using c#.net. Here we will use int.TryParse. This example we can use in the console application, asp.net core mvc application, windows application. 

In this tutorial example we will use the console application with .NET core. Now let's check the below code.

Validate Inter String

string intValue = "2312";
bool isnumber = int.TryParse(intValue, out int number);
if (isnumber)
{
    Console.WriteLine("This is a number and number is "+number);
}
else
{
    Console.WriteLine("Error: Not a number");
} 
In above code I have defined a string variable. To validate a string value is a number or not by using int.TryParse. Here one thing you need to check out int number. This will provide the number which we have passed. It act as an output parameter. Now you you dont want any value to return just to validate you ca pass "_" as shown below.
bool isnumber = int.TryParse(intValue, out _);
Now let's run the code to check the output.

Validate String is Number in C#.Net
Here in above code, you can check we are getting the pass string is a number. Now press F5 to check the output.

Sample Example Validate Integer Using C#.Net

Now let's check the other part, by passing a string value not a number in the same code. 

Not a Number in C#.net
Here in same code i have passed a string value and we are getting false. as this is not a number. 

String Not a Number in C#.Net

Validate Decimal String

We have already seen that to validate the pass string is an integer or not. Now in this code example we will validate the pass string is a decimal value or not. Please refer the below code. 
string decimalValue = "12.5";
bool isnumber = decimal.TryParse(decimalValue, out decimal number);
if (isnumber)
{
    Console.WriteLine("This is a decimal number and number is " + number);
}
else
{
    Console.WriteLine("Error: Not a decimal number");
} 
In above code i have string a variable in which I have passed a string value "12.5". Now we will validate whether this string decimal value is a decimal value or not. Now lets run the code to check the output.

String is a Decimal in c#.Net

In above code we are getting true. Now press F5 to check the output.

String is Not a Decimal in c#.Net

Now let's change the value and check the output. 

Not a Decimal Value in C#.Net

In above code we are getting false as this is not a decimal value.

String is Not a Decimal Value in C#.Net

Post a Comment