# Validating numeric input

*27-Nov-2017 10:56*

j Query, and some other javascript libraries already include such a function, usually called is Numeric. One way to check for Na N's is to check for numeric values that don't equal themselves, function is Number(n) function is Finite Number(n) function is Comparable Number(n) is Finite Number('Na N') false is Finite Number('Ox FF') true is Number('Na N') true is Number(1/0-1/0) true is Comparable Number('Na N') false is Comparable Number('Infinity') true Explained: Create a copy of itself, then converts the number into float, then compares itself with the original number, if it is still a number, (whether integer or float) , and matches the original number, that means, it is indeed a number. Positive hex numbers start with 0x and negative hex numbers start with -0x.

There is also a post on stackoverflow that has been widely accepted as the answer, the same general routine that the afore mentioned libraries are using. It works with numeric strings as well as plain numbers. Positive oct numbers start with 0 and negative oct numbers start with -0.

You can also use Regex to match more complex strings and detect if a string is using a "(xxx) xxx-xxxx" format, for instance.

Since this allows you to restrict the input values, you can safely parse the value to an integer. And about validation, all he has to do is check the is Numeric.

First, the code above would return true if the argument was an array of length 1, and that single element was of a type deemed as numeric by the above logic. This one takes most of what has already been mentioned into consideration, but includes hex and octal numbers, negative scientific, Infinity and has removed decimal scientific (4e3.2 is not valid).

The accepted answer failed your test #7 and I guess it's because you changed your mind. is Na N('blah') ""); // false $Numeric('-1'); // true $Numeric('-1.5'); // true $Numeric('0'); // true $Numeric('0.42'); // true $Numeric('.42'); // true $Numeric('0x89f'); // true (valid hexa number) $Numeric('99,999'); // false $Numeric('#abcdef'); // false $Numeric('1.2.3'); // false $Numeric(''); // false $Numeric('blah'); // false (because they are not actually part of the number as far as I concerned, they are separate operators): I needed this for a tokenizer, where sending the number to Java Script for evaluation wasn't an option...

Note: If you are using WPF, I don't think there is a Masked Text Box in the base libraries, however there are extensions available on Nu Get which may provide similar functionality. It gives you a true/false value, but doesn't give any real validation. I added the code to the if statement to better explain. Try Parse as davenewza recommended, but another alternative is to use the Visual Basic Is Numeric function from C#.