[snip]
Testing strings using regular expressions to see if they have
decimal places (and how many), surplus characters, scientific
notation, etc. requires exhaustive testing [...]
Not at all:
/^(0|[1-9])\d*$/
ensures that the string contains an integer with no leading zeros.
/^(-|+)?(0|[1-9])\d*$/
allows for signed integers.
To check for basic real numbers, it can be modified to:
/^(0|[1-9])\d*(\.\d+)?$/
which allows integer or real number inputs. To force decimal places and to
limit their number again, only simple modification is necessary:
/^(0|[1-9])\d*\.\d+$/ // must be real
/^(0|[1-9])\d*\.\d\d$/ // must be real with two decimal places
/^(0|[1-9])\d*\.\d{1,5}$/ // must be real with at most five d.p.
Scientific notation:
/^(0|[1-9])\d*\.\d+e(-|+)?\d+$/i
Optional scientific notation:
/^(0|[1-9])\d*\.\d+(e(-|+)?\d+)?$/i
Optional scientific notation with positive and negative numbers:
/^(-|+)?(0|[1-9])\d*\.\d+(e(-|+)?\d+)?$/i
Mandatory canonical scientific notation:
/^(-|+)?[1-9]\.\d+e(-|+)?[1-9]\d*$/i
Hexadecimal:
/^0x[0-9a-f]+$/i
[Note: these are untested]
The problem with using parseInt and parseFloat is that parsing stops at an
unrecognised character. That doesn't really tell you if the value's format
is correct or not, just that part of it converts to a number. If you want
check an input format, regular expressions are the best approach.
As you can see from the above, it doesn't take much effort once you've
established some basic patterns. After that point, it's simply a matter of
adding the components in the appropriate places.
How about:
var x = someValue;
if (x == parseInt(x) && x == parseFloat(x)) {
Calling parseInt without a radix argument can be unpredictable. Don't do
it.
[snip]
Mike