By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,693 Members | 1,822 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,693 IT Pros & Developers. It's quick & easy.

value is a number

P: n/a
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)

Maybe a regex?

Jeff


Jul 20 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
> 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)

Maybe a regex?


Use the isNaN() function, or better, use the isFinite() function.

if (!isFinite(test)) {alert(test + ' is not a number');}

NaN is a freaky thing. The comparison operators don't work with it.

http://www.crockford.com/javascript/survey.html
Jul 20 '05 #2

P: n/a
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.
Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.