How do I validate if a string represent a number?
Category: System, viewed: 2K time(s).
This examples shows couples of ways to determine if a string represent a numerical value. The number classes offers the Parse() and the TryParse() method that can be used to validate the string value.
The difference between this two methods is that the Parse() throws FormatException when the string doesn't represent a string. On the other side the TryParse() method return 0 to the out params and the method returns false if the string doesn't contains a valid numerical value.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Kodecsharp.Example.System
{
public class IsNumberDemo
{
public static void Main(string[] args)
{
IsNumberDemo demo = new IsNumberDemo();
//
// Calling the custom made isStringANumber to check if a string
// passed in is a valid integer / number value.
//
demo.isStringANumber("123"); // TRUE
demo.isStringANumber("-123"); // TRUE
demo.isStringANumber("ABC"); // FALSE
demo.isStringANumber("009"); // TRUE
//
// Below we try to convert is the string represent a float
// value but it doesn't, this causes a format exception is
// thrown by the Parse method.
//
try
{
float money = float.Parse("123.99Z");
}
catch (FormatException e)
{
Console.Error.WriteLine("Not a valid money.");
}
//
// Another way to validate is a string contains a valid number
// representation is to use the TryParse() method. This method
// instead of throwing a FormataException will return 0 (zero)
// if the string doesn't represent a numerical value, or the
// value is null and not in the range of Int32.MinValue and
// Int32.MaxValue.
//
int number;
bool isValid = Int32.TryParse("999z", out number);
Console.Out.WriteLine("Number = " + number + "; isValid = " + isValid);
Console.ReadLine();
}
public bool isStringANumber(string value)
{
bool result = false;
try
{
Int32.Parse(value);
result = true;
Console.Out.WriteLine(value + " = " + result);
}
catch (FormatException e)
{
Console.Out.WriteLine(value + " = " + result);
}
return result;
}
}
}