I believe it would be through the use of a regular expression. An expression that satisfies all your proposed tests would be:
^-?\d*\.?\d+$
Example in jsFiddle. Explaining:
^
string start
-?
with or without less at the front
\d*
zero or more digits (so that .42
valide, it is important to accept zero digits before the point)
\.?
point or no point
\d+
one or more digits
$
end of string
Other expressions could be used if one wished to accept a wider range of numbers - such as grouping thousands using the comma (American standard), allowing scientific notation using the e
(common in programming languages), allow a +
in front beyond only a minus, etc. And an "obvious" problem with the proposed expression is that it does not reject numbers with zeroes left.
In the end, it is a matter of precisely identifying what format a string is expected to have to be considered "numerical" and adjust the expression accordingly. It may get a little big, but in my opinion it’s even simpler than trying a parse manual (only if what you consider "number" does not fit into a regular language is that a more sophisticated method is needed).
Related question: "How to check if there are numbers inside an input with Javascript?" (I do not regard this as duplicate, as it is simply a matter of avoiding digits in a field, but the answers contain additional relevant information)
– mgibsonbr
Now that I’ve seen it, my '99,999' case should be
true
whereas it may be the number 99999 using,
as a thousand-seat delimiter– Andre Figueiredo
It’s hard to put an expression that works in all cases, but one way to adapt the expression to accept thousands separated by comma is to put it before the point:
(\,\d\d\d)*
. It’s not perfect, because an expression like that^-?\d*(\,\d\d\d)*\.?\d+$
would accept so much,123
how much12345,678
and even1,2345
(because the point is optional), that is, it has many false positives. It remains to be seen whether your concern is greater with false positives or false negatives, and adjust the regex accordingly. Or, of course, to make a function more complex and/or not based on regex...– mgibsonbr