560

Does anyone know how can I check whether a variable is a number or a string in JavaScript?

Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
Jin Yong
  • 42,698
  • 72
  • 141
  • 187

34 Answers34

500

If you're dealing with literal notation, and not constructors, you can use typeof:.

typeof "Hello World"; // string
typeof 123;           // number

If you're creating numbers and strings via a constructor, such as var foo = new String("foo"), you should keep in mind that typeof may return object for foo.

Perhaps a more foolproof method of checking the type would be to utilize the method found in underscore.js (annotated source can be found here),

var toString = Object.prototype.toString;

_.isString = function (obj) {
  return toString.call(obj) == '[object String]';
}

This returns a boolean true for the following:

_.isString("Jonathan"); // true
_.isString(new String("Jonathan")); // true
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 70
    which says "string" and "number" respectively – Thilo Sep 29 '10 at 02:47
  • 29
    This is not correct! There are two possible representations of a string. alert(typeof new String()) will output "Object". Worse, javascript will occasionally convert back and forth between the two representations behind the scenes for optimization purposes – George Mauer May 16 '11 at 20:33
  • 3
    @George According to the OP, only existing variables will be tested. – Sampson May 17 '11 at 20:27
  • 3
    Sure, but say I have function isString(str) { return typeof str === 'string' } some Java-convert can be using my method like so `var myString = new String("stuff I like"); isString(myString)` this returns false. Also, I'm not exactly sure how long the backgroiund conversion lasts, I know when I call "hi".length, "hi" gets converted into an object, not sure how soon it gets converted back again or if that is ever bound to the variable. – George Mauer May 18 '11 at 20:04
  • 9
    True, but wth would you want to use the String object anyway? – Félix Saparelli Jul 09 '11 at 00:57
  • @GeorgeMauer: A nice conclusion given in this [post](http://stackoverflow.com/a/4891964/629782) – vkGunasekaran Aug 01 '12 at 07:40
  • @JonathanSampson The comments you have showing String and Number as proper cases confused me because `typeof "Hello World" == 'String'` is false whereas `typeof "Hello World" == 'string'` is true. Maybe update the answer to make it more clear? – MikeSchinkel Oct 06 '12 at 18:39
  • I find that toString.call(obj) will often equal [pconnect wrapped native prototype] in Firefox rather than [object String]. However, using Object.prototype.toString.call(obj) works. – Stephen Simpson Dec 04 '12 at 10:43
  • 3
    try this: alert( typeof NaN); // you get 'number' - go figure – Quango Feb 02 '13 at 11:46
  • [Please prefer lodash libary in place of underscoreJs](https://stackoverflow.com/questions/13789618/differences-between-lodash-and-underscore) – RBT Jun 11 '17 at 09:55
  • This incomplete and wrong answer has sat here for 11 years uncorrected. I guess this proves S.O. premise that gamification would get correct answers voted to the top was wrong and it's time to re-evaluate how S.O. works. – gman Jun 23 '20 at 17:02
  • Note that typeof NaN === 'number' – Clemens Mar 17 '22 at 18:33
284

Best way to do that is using isNaN + type casting:

Updated all-in method:

function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }

The same using regex:

function isNumber(n) { return /^-?[\d.]+(?:e-?\d+)?$/.test(n); } 

------------------------

isNumber('123'); // true  
isNumber('123abc'); // false  
isNumber(5); // true  
isNumber('q345'); // false
isNumber(null); // false
isNumber(undefined); // false
isNumber(false); // false
isNumber('   '); // false
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
BitOfUniverse
  • 5,903
  • 1
  • 34
  • 38
77

The best way I have found is to either check for a method on the string, i.e.:

if (x.substring) {
// do string thing
} else{
// do other thing
}

or if you want to do something with the number check for a number property,

if (x.toFixed) {
// do number thing
} else {
// do other thing
}

This is sort of like "duck typing", it's up to you which way makes the most sense. I don't have enough karma to comment, but typeof fails for boxed strings and numbers, i.e.:

alert(typeof new String('Hello World'));
alert(typeof new Number(5));

will alert "object".

Alokito
  • 1,030
  • 8
  • 9
  • 2
    I find this to be better than `typeof` as it can always test for a string, whether primitive or String object. You just have to test for a method that's unique for the type you want. – ADTC Apr 07 '12 at 07:25
  • From the perspective of someone who has to maintain code, choosing this path could be confusing. "Why did they use substring and not pass any values? What business logic am I missing here?" At the very least, this needs to be paired with a comment explaining the logic involved. – Lemmings19 Dec 05 '16 at 21:50
  • 4
    @Lemmings19 It does not actually call the substring method, it only checks whether x has a substring method. – Alokito Jan 02 '17 at 17:00
  • 2
    I like the idea of this kind of duck typing but this will fail for things like `{substring:"hello"}`. I know for my purposes I just tested what the specific operation I needed to do (modulus) does for the type I needed to check for (on strings modulus returns undefined) then checked for that instead of getting it's type. – Tadhg McDonald-Jensen Sep 12 '18 at 14:59
51

Since ES2015 the correct way to check if a variable holds a valid number is Number.isFinite(value)

Examples:

Number.isFinite(Infinity)   // false
Number.isFinite(NaN)        // false
Number.isFinite(-Infinity)  // false

Number.isFinite(0)          // true
Number.isFinite(2e64)       // true

Number.isFinite('0')        // false
Number.isFinite(null)       // false
dain
  • 6,475
  • 1
  • 38
  • 47
adius
  • 13,685
  • 7
  • 45
  • 46
47

You're looking for isNaN():

console.log(!isNaN(123));
console.log(!isNaN(-1.23));
console.log(!isNaN(5-2));
console.log(!isNaN(0));
console.log(!isNaN("0"));
console.log(!isNaN("2"));
console.log(!isNaN("Hello"));
console.log(!isNaN("2005/12/12"));

See JavaScript isNaN() Function at MDN.

João Pimentel Ferreira
  • 14,289
  • 10
  • 80
  • 109
Jakob Gade
  • 12,319
  • 15
  • 70
  • 118
  • 3
    I find it strange that they would choose the inverse operation for the method name. Seems more intuitive to call isNumber(). – Nathan Taylor Aug 20 '09 at 02:54
  • 12
    It isn't actually an inverse operation of 'isNumber'. NaN is a special value of number in javascript. isNaN converts everything supplied to it to number and checks if the result is NaN or not. For strings like "25", you get incorrect result. – Chetan S Aug 20 '09 at 03:14
  • 3
    I just tested with "25" and it returned false - like I would expect. – Jakob Gade Aug 20 '09 at 05:01
  • But "25" is a string, not a number. – Matthew Crumley Aug 20 '09 at 05:15
  • 2
    NaN is a special value in the IEEE 754 Standard for Binary Floating-Point Arithmetic, not just a JavaScript thing. (Well, to be precise: *"the 9007199254740990 (that is, (2^53)-2) distinct “Not-a-Number” values of the IEEE Standard are represented in ECMAScript as a single special NaN value."*) – NickFitz Aug 20 '09 at 09:42
  • isNAN() will indeed return false for strings. However, for numbers, it will also return false. So if you want to test to see if x is a number, as OP stated, you would try "if (isNAN(x) && !isNAN(x))", and this would fail. – Sofi Software LLC Jun 19 '12 at 13:49
  • Does not work for empty string. `isNaN("")` returns `true`. – J. Hesters Aug 02 '18 at 18:09
  • 6
    Keep in mind that `isNaN` returns `false` for `null` (but `true` for `undefined`). – Toni Aug 08 '18 at 08:02
  • 2
    This is not sufficient, as it does not work for null – Jan Glaser Jan 11 '19 at 19:24
  • `!isNaN([]))`, `!isNaN([123])`, `!isNaN([123,456])`, `!isNaN(new Uint8Array(1))`, `!isNaN(new Uint8Array(2))` – gman Jun 23 '20 at 18:17
28

Check if the value is a string literal or String object:

function isString(o) {
    return typeof o == "string" || (typeof o == "object" && o.constructor === String);
}

Unit test:

function assertTrue(value, message) {
    if (!value) {
        alert("Assertion error: " + message);
    }
}

function assertFalse(value, message)
{
    assertTrue(!value, message);
}

assertTrue(isString("string literal"), "number literal");
assertTrue(isString(new String("String object")), "String object");
assertFalse(isString(1), "number literal");
assertFalse(isString(true), "boolean literal");
assertFalse(isString({}), "object");

Checking for a number is similar:

function isNumber(o) {
    return typeof o == "number" || (typeof o == "object" && o.constructor === Number);
}
snorbi
  • 2,590
  • 26
  • 36
17

Try this,

<script>
var regInteger = /^-?\d+$/;

function isInteger( str ) {    
    return regInteger.test( str );
}

if(isInteger("1a11")) {
   console.log( 'Integer' );
} else {
   console.log( 'Non Integer' );
}
</script>
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
14
//testing data types accurately in JavaScript (opposed to "typeof")
//from http://bonsaiden.github.com/JavaScript-Garden/
function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

//basic usage
is('String', 'test'); // true
is('Array', true); // false

Or adapt it to return an unknown type:

function realTypeOf(obj) {
    return Object.prototype.toString.call(obj).slice(8, -1);
}

//usage
realTypeOf(999); // 'Number'

May 12, 2012 Update: Full example at Javascript: A Better typeof.

mrrena
  • 149
  • 1
  • 3
  • Still room for improvement regarding `realTypeOf`: `realTypeOf(NaN) -> "Number"` which is same behaviour as `typeof` agreed but still far from ideal. – Max Aug 24 '12 at 08:09
14

Best way to do this:

function isNumber(num) {
  return (typeof num == 'string' || typeof num == 'number') && !isNaN(num - 0) && num !== '';
};

This satisfies the following test cases:

assertEquals("ISNUMBER-True: 0", true, isNumber(0));
assertEquals("ISNUMBER-True: 1", true, isNumber(-1));
assertEquals("ISNUMBER-True: 2", true, isNumber(-500));
assertEquals("ISNUMBER-True: 3", true, isNumber(15000));
assertEquals("ISNUMBER-True: 4", true, isNumber(0.35));
assertEquals("ISNUMBER-True: 5", true, isNumber(-10.35));
assertEquals("ISNUMBER-True: 6", true, isNumber(2.534e25));
assertEquals("ISNUMBER-True: 7", true, isNumber('2.534e25'));
assertEquals("ISNUMBER-True: 8", true, isNumber('52334'));
assertEquals("ISNUMBER-True: 9", true, isNumber('-234'));

assertEquals("ISNUMBER-False: 0", false, isNumber(NaN));
assertEquals("ISNUMBER-False: 1", false, isNumber({}));
assertEquals("ISNUMBER-False: 2", false, isNumber([]));
assertEquals("ISNUMBER-False: 3", false, isNumber(''));
assertEquals("ISNUMBER-False: 4", false, isNumber('one'));
assertEquals("ISNUMBER-False: 5", false, isNumber(true));
assertEquals("ISNUMBER-False: 6", false, isNumber(false));
assertEquals("ISNUMBER-False: 7", false, isNumber());
assertEquals("ISNUMBER-False: 8", false, isNumber(undefined));
assertEquals("ISNUMBER-False: 9", false, isNumber(null));
Sitch
  • 141
  • 1
  • 2
13

Simple and thorough:

function isNumber(x) {
  return parseFloat(x) == x
};

Test cases:

console.log('***TRUE CASES***');
console.log(isNumber(0));
console.log(isNumber(-1));
console.log(isNumber(-500));
console.log(isNumber(15000));
console.log(isNumber(0.35));
console.log(isNumber(-10.35));
console.log(isNumber(2.534e25));
console.log(isNumber('2.534e25'));
console.log(isNumber('52334'));
console.log(isNumber('-234'));
console.log(isNumber(Infinity));
console.log(isNumber(-Infinity));
console.log(isNumber('Infinity'));
console.log(isNumber('-Infinity'));

console.log('***FALSE CASES***');
console.log(isNumber(NaN));
console.log(isNumber({}));
console.log(isNumber([]));
console.log(isNumber(''));
console.log(isNumber('one'));
console.log(isNumber(true));
console.log(isNumber(false));
console.log(isNumber());
console.log(isNumber(undefined));
console.log(isNumber(null));
console.log(isNumber('-234aa'));
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
  • this answer helped, although it doesn't really answer the original question :) – Roey Jul 14 '20 at 13:00
  • Wait, isn't this wrong? `const myVar = "5"; // Set it to a string. isNumber(myVar); // True, but it should be false since this variable is a string not a number.` – Don P Aug 08 '21 at 19:53
  • 1
    @DonP Yeah, as you and Roey pointed out, my answer doesn't answer the original question. I posted it here because it seemed like a useful discovery and a shorter/better version of the many answers here that are instead concerned with determining whether a value is [either a regular number already or a string that can be converted to one] or not. – MarredCheese Aug 08 '21 at 22:26
10

Here's an approach based on the idea of coercing the input to a number or string by adding zero or the null string, and then do a typed equality comparison.

function is_number(x) { return x === x+0;  }
function is_string(x) { return x === x+""; }

For some unfathomable reason, x===x+0 seems to perform better than x===+x.

Are there any cases where this fails?

In the same vein:

function is_boolean(x) { return x === !!x; }

This appears to be mildly faster than either x===true || x===false or typeof x==="boolean" (and much faster than x===Boolean(x)).

Then there's also

function is_regexp(x)  { return x === RegExp(x); }

All these depend on the existence of an "identity" operation particular to each type which can be applied to any value and reliably produce a value of the type in question. I cannot think of such an operation for dates.

For NaN, there is

function is_nan(x) { return x !== x;}

This is basically underscore's version, and as it stands is about four times faster than isNaN(), but the comments in the underscore source mention that "NaN is the only number that does not equal itself" and adds a check for _.isNumber. Why? What other objects would not equal themselves? Also, underscore uses x !== +x--but what difference could the + here make?

Then for the paranoid:

function is_undefined(x) { return x===[][0]; }

or this

function is_undefined(x) { return x===void(0); }
c-smile
  • 26,734
  • 7
  • 59
  • 86
9

Or just use the invert of isNaN():

if(!isNaN(data))
  do something with the number
else
  it is a string

And yes, using jQuery's $.isNumeric() is more fun for the buck.

MarredCheese
  • 17,541
  • 8
  • 92
  • 91
osomanden
  • 599
  • 1
  • 10
  • 26
8

I think converting the var to a string decreases the performance, at least this test performed in the latest browsers shows so.

So if you care about performance, I would, I'd use this:

typeof str === "string" || str instanceof String

for checking if the variable is a string (even if you use var str = new String("foo"), str instanceof String would return true).

As for checking if it's a number I would go for the native: isNaN; function.

Roland
  • 9,321
  • 17
  • 79
  • 135
8

Can you just divide it by 1?

I assume the issue would be a string input like: "123ABG"

var Check = "123ABG"

if(Check == Check / 1)
{
alert("This IS a number \n")
}

else
{
alert("This is NOT a number \n")
}

Just a way I did it recently.

Luke
  • 81
  • 1
  • 1
7

Beware that typeof NaN is... 'number'

typeof NaN === 'number'; // true
Ermac
  • 1,181
  • 1
  • 8
  • 12
7

uh, how about just:

function IsString(obj) {
    return obj !== undefined && obj != null && obj.toLowerCase !== undefined;
}

After further review many months later, this only guarantees obj is an object that has the method or property name toLowerCase defined. I am ashamed of my answer. Please see top-voted typeof one.

ZagNut
  • 1,431
  • 15
  • 20
5

jQuery uses this:

function isNumber(obj) {
  return !isNaN( parseFloat( obj ) ) && isFinite( obj );
}
4

This solution resolves many of the issues raised here!

This is by far the most reliable method I have used by far. I did not invent this, and cannot recall where I originally found it. But it works where other techniques fail:

// Begin public utility /getVarType/
// Returns 'Function', 'Object', 'Array',
// 'String', 'Number', 'Boolean', or 'Undefined'
getVarType = function ( data ){
  if (undefined === data ){ return 'Undefined'; }
  if (data === null ){ return 'Null'; }
  return {}.toString.call(data).slice(8, -1);
};  
// End public utility /getVarType/

Example of correctness

var str = new String();
console.warn( getVarType(str) ); // Reports "String"    
console.warn( typeof str );      // Reports "object"

var num = new Number();
console.warn( getVarType(num) ); // Reports "Number"
console.warn( typeof num );      // Reports "object"

var list = [];
console.warn( getVarType( list ) ); // Reports "Array"
console.warn( typeof list );        // Reports "object"
Michael Mikowski
  • 1,269
  • 1
  • 10
  • 21
  • Tarazaburo, I don't know where you get your data, but a little benchmarkining is in order: – Michael Mikowski Jun 29 '13 at 19:27
  • I don't find this "really slow". Testing speed over 1 million iterations, I find it no worse than half the speed of the native `typeof` method (0.788s vs 1.481s) on Chrome. This certainly is acceptable performance considering the improved results. Why do you think it is "really slow?" Maybe it is - in IE6/7/8? But *everything* is "really slow" in those browsers. – Michael Mikowski Jun 29 '13 at 19:34
  • Well, I said that because I had already done the benchmarking. Put together a new little one at http://jsperf.com/check-typeof-number-again, and `typeof` is 100x faster, what am I missing? –  Jul 04 '13 at 15:40
  • You are missing the fact that 3m ops/s is a non-issue for most code when checking type. I wouldn't call that "really slow" by any measure. My benchmark looked like this: var i,k, start=+new Date(); for ( i = 0; i < 1000000; i++ ){ k = typeof( 'foo' ); k = typeof( 123.5 ); }; end=+new Date(); console.log( end - start); – Michael Mikowski Jul 06 '13 at 21:27
  • The delta with the alternate is 2-3x: var i,k, start=+new Date(); for ( i = 0; i < 1000000; i++ ){ k = getVarType( 'foo' ); k = getVarType( 123.5 ); }; end=+new Date(); console.log( end - start); – Michael Mikowski Jul 06 '13 at 21:35
  • Also compare these two. I introduced random strings to minimize the effects of caching optimization. Using getVarType we get 4383ms; replacing that with typeof gets us 2211ms. So typeof is ~2x faster. I'm not going to lose any sleep over that. CODE: var i,k, start=+new Date(); for ( i = 0; i < 1000000; i++ ){ k = getVarType( 'foo' + String(Math.random(0)) ); k = getVarType( 100 * Math.random(0) ); } end=+new Date(); console.log( end - start); – Michael Mikowski Jul 06 '13 at 21:42
  • To be fair, I recognize that typeof is virtually a no-op and toString is much slower. But in read-world code, the expense of getVarType() is trivial compared to surrounding code, as illustrated above. If I need to check type three times in a code block, it might cost me 0.003ms (getVarType) or 0.000ms (typeof). That speed difference rarely matters; the correctness, however, does. – Michael Mikowski Jul 06 '13 at 21:54
  • Well, of course you are right that, in the overall scheme of things, this may make no difference. I meant "very slow" in relative, not absolute, terms. But I'm curious about your point regarding "correctness"; in which case is `typeof x==="number"` not correct? –  Jul 08 '13 at 02:52
  • Hi Torazaboru: The correctness issue results when you do this: var num = new Number(); console.log( typeof( num ) ); - This reports an object, not a number. Similar results exist with arrays, strings, and so on. See the examples listed in the original post. Personally, I do use typeof in certain situations, but one needs to know its limitations :) – Michael Mikowski Jul 08 '13 at 21:27
  • Torazaboru: Please see my new answer here http://stackoverflow.com/questions/17440517/. In summary, there are some edge cases, especially when working with Firefox DOM elements, that require special handling. – Michael Mikowski Jul 11 '13 at 00:34
  • I imagine the number of numbers in the world that are created with the Number() constructor can be counted on the fingers of one hand. Can anyone provide a use case for it in the first place? –  Jul 12 '13 at 11:43
  • A DOM element is a DOM element, not a number or a string, so how does that pertain to this question? If you are referring to pseudo-arrays such as are returned by `getElementsByTagName`, then those are not arrays, and I don't want some type-checking system telling me they are. –  Jul 12 '13 at 11:45
  • I *am* referring to psuedo arrays, such as those provided by document.styleSheets. For my purposes, I generally like to see these reported as arrays. One can argue that all JavaScript arrays are psuedo-arrays. It depends where one wants to draw the line. – Michael Mikowski Jul 12 '13 at 23:35
  • The reality is that typeof provides incorrect results for Number, String, Array, Boolean, and other such constuctors. Yeah, few use Number, but plenty use Array. The main goal of my routine is to identify use-intent as correctly as possible for the provided variable. Absolute speed is important (e.g. 3000 ops/ms is good), but correctness is valued over speed. – Michael Mikowski Jul 12 '13 at 23:42
4

Jsut an FYI, if you're using jQuery you have

$.isNumeric() 

to handle this. More details on http://api.jquery.com/jQuery.isNumeric/

Angelos
  • 227
  • 1
  • 2
  • 10
3

since a string as '1234' with typeof will show 'string', and the inverse cannot ever happen (typeof 123 will always be number), the best is to use a simple regex /^\-?\d+$/.test(var). Or a more advanced to match floats, integers and negative numbers, /^[\-\+]?[\d]+\.?(\d+)?$/ The important side of .test is that it WON'T throw an exception if the var isn't an string, the value can be anything.

var val, regex = /^[\-\+]?[\d]+\.?(\d+)?$/;

regex.test(val)       // false 
val = '1234';
regex.test(val)       // true
val = '-213';
regex.test(val)       // true
val = '-213.2312';
regex.test(val)       // true
val = '+213.2312';
regex.test(val)       // true
val = 123;
regex.test(val)       // true
val = new Number(123);
regex.test(val)       // true
val = new String('123');
regex.test(val)       // true
val = '1234e';
regex.test(val)       // false 
val = {};
regex.test(val)       // false 
val = false;
regex.test(val)       // false 
regex.test(undefined) // false 
regex.test(null)      // false 
regex.test(window)    // false 
regex.test(document)  // false 

If you are looking for the real type, then typeof alone will do.

pocesar
  • 6,860
  • 6
  • 56
  • 88
3

@BitOfUniverse's answer is good, and I come up with a new way:

function isNum(n) {
    return !isNaN(n/0);
}

isNum('')  // false
isNum(2)   // true
isNum('2k') // false
isNum('2')  //true

I know 0 can't be dividend, but here the function works perfectly.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
towry
  • 4,131
  • 1
  • 18
  • 25
3

typeof works very well for me in most case. You can try using an if statement

if(typeof x === 'string' || typeof x === 'number') {
    console.log("Your statement");
}

where x is any variable name of your choice

Tanah
  • 449
  • 4
  • 8
3

Type checking

You can check the type of variable by using typeof operator:

typeof variable

Value checking

The code below returns true for numbers and false for anything else:

!isNaN(+variable);
Amir Fo
  • 5,163
  • 1
  • 43
  • 51
  • var variable= '123'; console.log(!isNaN(+variable)); gives true although it is a string and not a number type – JustAMartin Jan 28 '20 at 12:34
  • Because '123' is a number! If you want to know the type of the variable, You can easily use `typeof` operator! @JustAMartin – Amir Fo Jan 28 '20 at 13:12
  • Yes, but the original question was to distinguish any string-typed variables from number-typed variables. '123` is still a string. If I pass 123, the answer should be `number` but if I pass '123' or 'abc' or any other quoted literal, it is a string, and it does not matter if it can be parsed into a number or not. – JustAMartin Jan 28 '20 at 14:11
3

XOR operation can be used to detect number or string. number ^ 0 will always give the same number as output and string ^ 0 will give 0 as output.

Example: 
   1)  2 ^ 0 = 2
   2)  '2' ^ 0  = 2
   3)  'Str' ^ 0 = 0
Himanshu Shekhar
  • 1,196
  • 1
  • 16
  • 35
3

the best way i found which also thinks of positive and negative numbers is from : O'Reilly Javascript and DHTML Cookbook :

function isNumber(elem) {
var str = elem.value;
var oneDecimal = false;
var oneChar = 0;
// make sure value hasn't cast to a number data type
str = str.toString( );
for (var i = 0; i < str.length; i++) {
    oneChar = str.charAt(i).charCodeAt(0);
    // OK for minus sign as first character
    if (oneChar =  = 45) {
        if (i =  = 0) {
            continue;
        } else {
            alert("Only the first character may be a minus sign.");
            return false;
        }
    }
    // OK for one decimal point
    if (oneChar =  = 46) {
        if (!oneDecimal) {
            oneDecimal = true;
            continue;
        } else {
            alert("Only one decimal is allowed in a number.");
            return false;
        }
    }
    // characters outside of 0 through 9 not OK
    if (oneChar < 48 || oneChar > 57) {
        alert("Enter only numbers into the field.");
        return false;
    }
}
return true;

}

Alex Peta
  • 1,407
  • 1
  • 15
  • 26
3

Errr? Just use regular expressions! :)

function isInteger(val) {
  return val.match(/^[0-9]$/)
}

function isFloat(val) {
  return val.match(/^[0-9]*/\.[0-9]+$/)
}
hackerdiehack
  • 372
  • 3
  • 11
1
function IsNumeric(num) {
    return ((num >=0 || num < 0)&& (parseInt(num)==num) );
}
hosein
  • 519
  • 5
  • 25
1

For detecting numbers, the following passage from JavaScript: The Good Parts by Douglas Crockford is relevant:

The isFinite function is the best way of determining whether a value can be used as a number because it rejects NaN and Infinity . Unfortunately, isFinite will attempt to convert its operand to a number, so it is not a good test if a value is not actually a number. You may want to define your own isNumber function:

var isNumber = function isNumber(value) { return typeof value === 'number' &&
            isFinite(value);
};
Stephen Niedzielski
  • 2,497
  • 1
  • 28
  • 34
0

Simply use

myVar.constructor == String

or

myVar.constructor == Number

if you want to handle strings defined as objects or literals and saves you don't want to use a helper function.

Jonathon
  • 155
  • 1
  • 11
0

Very late to the party; however, the following has always worked well for me when I want to check whether some input is either a string or a number in one shot.

return !!Object.prototype.toString.call(input).match(/\[object (String|Number)\]/);
Wil Moore III
  • 6,968
  • 3
  • 36
  • 49
0

Created a jsperf on the checking if a variable is a number. Quite interesting! typeof actually has a performance use. Using typeof for anything other than numbers, generally goes a 1/3rd the speed as a variable.constructor since the majority of data types in javascript are Objects; numbers are not!

http://jsperf.com/jemiloii-fastest-method-to-check-if-type-is-a-number

typeof variable === 'number'| fastest | if you want a number, such as 5, and not '5'
typeof parseFloat(variable) === 'number'| fastest | if you want a number, such as 5, and '5'

isNaN() is slower, but not that much slower. I had high hopes for parseInt and parseFloat, however they were horribly slower.

jemiloii
  • 24,594
  • 7
  • 54
  • 83
0

What do you thing about this one?

const numberOrString='10' 
const isNumber = !isNaN(numberOrString*1) 
Zoe
  • 27,060
  • 21
  • 118
  • 148
Yoraco Gonzales
  • 727
  • 10
  • 18
0

Efficiency test

I know which way I'll be using...

function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }

function isNumberRE(n) { return /^-?[\d.]+(?:e-?\d+)?$/.test(n); } 

function test(fn, timerLabel) {
    console.time(timerLabel)
    for (i = 0; i < 1000000; i++) {
        const num = Math.random() * 100
        const isNum = fn(num)
    }
    console.timeEnd(timerLabel)
}

test(isNumber, "Normal way")

test(isNumberRE, "RegEx way")
Normal way: 25.103271484375 ms
RegEx way: 334.791015625 ms
Steve
  • 4,372
  • 26
  • 37
0

Like others, I'm addicted to strong typing (even though I love JS)

And in my code, I happened to need to make a distinction between a number and a string, to perform 2 very different types of operations.

Rather than a spiel log:

let int =  123,  str = '123';

console.log( int.constructor===Number, str.constructor===String ); //  true true

console.log( typeof int === 'number', typeof str === 'number');   //  true false

console.log (Number(int)===int, Number(str)===str )               //  true false
// or :
console.log (String(int)===int, String(str)===str )              //  false true

// the shortest :
console.log( +int===int, +str===str );                          //  true false

I therefore mainly use, especially in ternary tests.

let res = (+X===X) ? stuff_to_do_with_a_Number(X) : stuff_to_do_with_a_String(X);

Of course, this must be handled with care.

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40