JRS: In article <QX*****************@newsread1.news.atl.earthlink. net>,
seen in news:comp.lang.javascript, Jeff Thies <no****@nospam.net> posted
at Tue, 18 Nov 2003 16:40:16 :-
I'm trying to test if a value is a number.
I thought I could do this:
var test='not_a_number';
var test2='4.00';
num_test=parseFloat(test);
if(num_test == 'NaN'){alert('that was not a number')}
But that doesn't work. (at least not in NS)
NaN is not a number; since this might occur in many ways, it is equal to
nothing, not even itself. But 'NaN' is a perfectly good non-numeric
string, and +'NaN' gives NaN without being equal to it.
Maybe a regex?
Yes. In any reasonable application in which it is right to validate a
number, it is likely that the set of suitable numbers is much smaller
than the set of possible numbers. Likewise formats.
You may in practice want non-negative integers, with no need to allow
the format 1e2; in that case test with RegExp /^\d+$/ - see
<URL:http://www.merlyn.demon.co.uk/js-maths.htm#Valid>.
Once the format is OK, you can convert the string to a number in safety
with unary +
Numeric = +Stringy.value
and then if necessary do further tests with arithmetic comparison.
E.G. : In US notation, seconds format is RegExp /^[0-5]\d$/ = 00..59 but
there is nothing quite so simple for hours 01..12 ; /^0[1-9]|1[0-2]$/ .
--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://jibbering.com/faq/> Jim Ley's FAQ for news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> JS maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/JS/&c., FAQ topics, links.