test for numbers containing a decimal point
-
I know that I can use javascript to test for a number using the below, but I am having trouble figuring out how to use javascript to test for the entry of for example 100.00 or 100, the decimal point is messsing me up. Any help would be appreciated. function TestKeyPress( obj, event ) { var curChar = String.fromCharCode( event.keyCode ); var inpStr = obj.value + curChar window.status = ''; obj.title = ''; result = inpStr.match( '^[0-9]+$' ); if ( ! result ) { window.status = 'Please enter only numbers.'; obj.title = window.status; event.returnValue = false; event.cancel = true; } }
-
I know that I can use javascript to test for a number using the below, but I am having trouble figuring out how to use javascript to test for the entry of for example 100.00 or 100, the decimal point is messsing me up. Any help would be appreciated. function TestKeyPress( obj, event ) { var curChar = String.fromCharCode( event.keyCode ); var inpStr = obj.value + curChar window.status = ''; obj.title = ''; result = inpStr.match( '^[0-9]+$' ); if ( ! result ) { window.status = 'Please enter only numbers.'; obj.title = window.status; event.returnValue = false; event.cancel = true; } }
There's regex in jscript ? '^[0-9]+\.?[0-9]?$' should do it. ( test for number, optional . and then optional number after the . ) Christian Graus - Microsoft MVP - C++
-
I know that I can use javascript to test for a number using the below, but I am having trouble figuring out how to use javascript to test for the entry of for example 100.00 or 100, the decimal point is messsing me up. Any help would be appreciated. function TestKeyPress( obj, event ) { var curChar = String.fromCharCode( event.keyCode ); var inpStr = obj.value + curChar window.status = ''; obj.title = ''; result = inpStr.match( '^[0-9]+$' ); if ( ! result ) { window.status = 'Please enter only numbers.'; obj.title = window.status; event.returnValue = false; event.cancel = true; } }
To match either an integer or floating point number, use this pattern:
^(\d+)|(\d*\.\d+)$
The first part (\d+) will match an integer, e.g. one or more digits. The secont part (\d*\.\d+) will match a floating point number, e.g. optinal digits before the decimal point and one or more digits after. --- b { font-weight: normal; }