This article will give you a way to determine if a given
string has a valid number style (
Currency, etc.) according to specified/current culture.
In all VBScript and Visual Basic applications, there is a built-in function called
IsCurrency, but in C# there is no built-in function with the same functionality.
I have investigated a little and found out that all given solutions always use
try catch to find out if the given
string value can be parsed.
That seemed like a good way to test it, BUT what if the number contains commas or a currency sign?
Then I have to add another check to this code and strip down the non numeric sign and test the result.
Here I present a simple way that is supported by C#.
In the code shown below, I actually use a built-in functionality of C# to determine if a given
string value stands up to the requirements I want.
public bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle)
The above function allow me to test if the given
string stands up to one or more of the following styles:
- Hex Number
A more detailed list and explanation regarding
System.Globalization.NumberStyles can be found here.
If you want to test for an integer number, then do the following:
If you want to test for an integer number separated with commas, then do the following:
isNumeric("42,000", System.Globalization.NumberStyles.Integer |
Using Other Cultures
I use the current culture as shown in the code below.
A list of all available culture names can be obtained here.
public bool isNumeric
(string val, System.Globalization.NumberStyles NumberStyle, string CultureName)
return Double.TryParse(val,NumberStyle,new System.Globalization.CultureInfo
There are many ways to approach this problem, I chose the one that suits beginner levels and does not involve any Regular Expression which requires a higher level of expertise.
If you are interested in a solution that involves Regular Expressions, please take a look at the following links:
Enjoy and tell me your findings.
- 7th March, 2006: Initial post
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.