Friday, 9 December 2011

Check if a String Value Is Numeric in C#

This article will give you a way to determine if a given string has a valid number style (Integer, Float, Currency, etc.) according to specified format.
In all VBScript and Visual Basic applications, there is a built-in function called IsNumeric / IsCurrency, but in C# there is no built-in function with the same functionality.
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, NumberStyles NumberStyle)
    Double result;
    return Double.TryParse(val, NumberStyle,
      System.Globalization.CultureInfo.CurrentCulture, out result);

The above function allows me to test if the given string stands up to one or more of the following styles:
  1. Hex Number
  2. Number
  3. Currency
  4. Float

isNumeric("7000", System.Globalization.NumberStyles.Integer)
If you want to test for an integer number separated with commas, then do the following:
isNumeric("7,51,000", System.Globalization.NumberStyles.Integer |

No comments:

Post a Comment