Test is numeric?

Hi all,

Im creating a postage calc for an Aussie client, and I need to check the input is numeric before I run it through a switch to decide which State/Territory the postcode belongs too (im guessing thats the best idea).

What would be the best way to check the input is numeric/integer before I run a test on it?

Many thanks!

This page probably will assist: http://andrewpeace.com/javascript-is-numeric.html

Great link, thanks rguy!

You’re welcome, glad it helped.


<script type=“text/javascript”>
function form_input_is_numeric(input){
return !isNaN(input);
}
</script>



That function will pronunce an empty string to be numeric, so without supporting validation its use is inadvisable.

If you’re getting value from a form, you can just use Number() to turn the string value in to a number.

var postcode = Number(form.elements.postcode.value);

or, If you want to ensure that it’s an integer, parseInt() can be used instead.

var postcode = parseInt(form.elements.postcode.value, 10);
Number( "" ) == 0

or, If you want to ensure that it’s an integer, parseInt() can be used instead.

var postcode = parseInt(form.elements.postcode.value, 10);

That ensures that it starts with an integer.

parseInt( "1oo", 10) == 1

The most satisfactory solution I’ve seen is to use isFinite combined with parseFloat to eliminate null strings.

return !isNaN( parseFloat( n ) ) && isFinite( n );