Is numeric?

A

Aaron DeLoach

I may have cross-posted this... :-(

I'm a VB programmer getting *way* to deep into this wonderful new JS
venture. I looked around for a function like VBs' IsNumeric without much
success. I had to roll my own. Does anyone see any bugs in this?

function IsNumeric(expression) {

var nums = "0123456789";

if (expression.length==0)return(false);

for (var n=0; n < expression.length; n++){

if(nums.indexOf(expression.charAt(n))==-1)return(false);


}

return(true);

}
 
A

Aaron DeLoach

I tried the isNaN() with unsatisfactory results. I don't quite understand
*how* it works but your post chopped the code from eight lines to three (I
like efficient code). I'll have to read the M$ link you provided. Thanks
for your help.
 
L

Lasse Reichstein Nielsen

Steve van Dongen said:
I just wanted to note that
isn't a very good test because it allows bad things through. For
example, parseInt("40lakjsdlfj") is 40, which is a number, but the
original input string (obviously) isn't. It also blocks valid inputs
like "09" which is a valid decimal number but not a valid octal
number.

Valid point. Try this instead

function isNumeric(value) {
return typeof value != "boolean" && value !== null && !isNaN(+ value);
}

The prefix "+" converts its argument to a number just like the Number
function.
The extra checks are there because booleans and null can be converted
to the numbers 0 and 1.
return (String(expression).search(/^\d+$/) != -1);

You can make this a little shorter:
return String(expression).match(/^\d+$/);
 
D

Dr John Stockton

JRS: In article <[email protected]>, seen in
news:comp.lang.javascript said:
I may have cross-posted this... :-(

You did not; perhaps you mean multi-posted.
I looked around for a function like VBs' IsNumeric without much
success.

Without an accurate knowledge of the VB function it is difficult to
emulate it reliably. For example. what about an empty string?

function IsNumeric(S) { return S > '' && ! isNaN(S) }

seems reasonable. But, for me, it accepts 1e9999 - Infinity is a
number.

function IsNumeric(S) { return S > '' && isFinite(S) }

However, in any practical application, the permissible input is likely
to be more limited; use a RegExp to test for, say, 1..5 decimal digits
preceded by sign or space.

OK = /^[-+ ]?\d{1,5}$/.test(S)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,077
Messages
2,570,569
Members
47,205
Latest member
KelleM857

Latest Threads

Top