How do I know if a variable is of the Javascript Number type?

Asked

Viewed 43,303 times

20

In javascript, because there is no declaration of the types of variables such as Integer, String, Boolean, etc., it is a difficult task to know what kind of value you are dealing with in a given variable.

So, to make my code consistent, I would like to know how to proceed to check if a variable is a Numeral or not.

How is this possible?

  • 3

    Maybe you’ll find the Typescript interesting.

7 answers

17


It is simple to know if a variable is Numero or not because there is a native Javascript operator that says the type of its variable, which would be the operator typeof, there are some types of Javascript variables known:

typeof 0;    //number
typeof 1;    //number
typeof 0.5;  //number

typeof '1';  //string
typeof 'a';  //string
typeof " ";  //string

typeof true; //boolean
typeof false;//boolean

typeof [1,2]         //object
typeof {"obj":[2,3]} //object
typeof {"obj":"3"}   //object

typeof function(){alert('foo')} //function

typeof a    //undefined -- note que nao declarei a
typeof null //null é um object(wtf)

So here’s an example of a function that checks if the type is number

function isNumber(val){
  return typeof val === "number"
}

By testing all the values I exemplified above, you will see that only the ones with type number that I commented will return true.

We can also modify "number" by another type to create a function that checks whether it is string for example, or if it is boolean, it’s that simple.

In fact, it is a disadvantage, depending on the point of view, in Javascript it is not necessary to declare the type and variable before using it.

  • 4

    Clarification: the typeof is not a function, is an operator. You can simply use typeof 1, without the parentheses. When you use the parentheses you are actually creating a Expression, and the whole thing is interpreted like this: typeof(1) > typeof and (1)> typeof and 1 > typeof 1.

  • I didn’t understand @bfavaretto could explain better?

  • 1

    Is an operator unary (that asks for a single argument), as well as ++, !, delete, among others. It is not a function, so it does not need parentheses, it is not an invocation. It works with parentheses because the (1) is processed first, as an expression, understood as 1, and then passed to the operator.

  • +1 reading the question again, I agree that your answer is more directed to the question, only I do not delete my answer as it can serve as information for cases similar to the one of the question that do not exactly require typing.

  • 1

    Ah, and a prank I remembered seeing Anthony Acciolly’s reply: typeof NaN === "number".

  • now I understand @bfavaretto - and about the catch, bá javascript guy always has a way of not working right? kkk

Show 1 more comment

11

If you’re not looking to verify something is a number, but if it behaves as if it were, can use this function:

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

The idea is that "1" is, for all intents and purposes, a number. After all you can write "1"+2.

Based on a reply by SO CMS.

  • 2

    This was the implementation used by jQuery until that commit which introduced the following strategy return n - parseFloat(n) >= 0;

10

Well, Paulo Roberto posted the correct answer - and what he certainly had in mind when he asked the question - to find out if a variable "contains" a number. Some of the other answers have tried to go down the path of finding out if a certain variable "represents" a number; a fairly common problem, and a task that may not be so easy in Javascript (as in most dynamic languages).

While I may be extrapolating the question, since Paul did not mention this point or mark libraries in the question. I think it’s fair to point out that the notorious jQuery has the function jQuery.isNumeric() to solve this second problem of types that may behave as (or be converted to) numbers. When in doubt, between writing regular expressions or combinations of methods isXXX, I believe that it is worth using the library, thus avoiding the various tricks of the language:

Examples of documentation:

$.isNumeric( "-10" );     // true
$.isNumeric( 16 );        // true
$.isNumeric( 0xFF );      // true
$.isNumeric( "0xFF" );    // true
$.isNumeric( "8e5" );     // true (exponential notation string)
$.isNumeric( 3.1415 );    // true
$.isNumeric( +10 );       // true
$.isNumeric( 0144 );      // true (octal integer literal)
$.isNumeric( "" );        // false
$.isNumeric({});          // false (empty object)
$.isNumeric( NaN );       // false
$.isNumeric( null );      // false
$.isNumeric( true );      // false
$.isNumeric( Infinity );  // false
$.isNumeric( undefined ); // false
  • Within the topic of variable types in dynamic languages like Javascript, recommend video Wat (link) for those who want to have a good laugh (the NaNNaNNaNNaNis especially funny).

9

Javascript has a native function to check if it is not numerical by testing it next to weak typing isNaN.

So if you want to know if it’s numerical you can use !isNaN and it will return true to any numerical value independent of typing.

Example:

!isNaN(1); // true
!isNaN('1'); // true
!isNaN('0'); // true
!isNaN(''); // true (no caso é considerado zero pelo Javascript)
!isNaN(false); // true (no caso é considerado zero pelo Javascript)
!isNaN(true); // true (no caso é considerado um pelo Javascript)

!isNaN('texto'); // false
!isNaN({}); // false

Example of conditional use:

var numero = '12345';
if (!isNaN(numero)) {
    // se é um numero vai cari aqui
}

Which is a compact way of writing that:

if (!isNaN(numero) === true) {
    // se é um numero vai cari aqui
}

// ou (repare que eu removi a negação antes da função)

if (isNaN(numero) === false) {
    // se é um numero vai cari aqui
}

Not to include the value Infinity which is native and can be represented by a string, you can match the function isFinite, example:

!isNaN(numero) && isFinite(numero); // Se for número e não for Infinity vai retornar true
  • I don’t understand why 1 === isNaN returns false? explain to me better how it works

  • 1

    isNaN is a function, use !isNaN(1) === true

  • Yes, of course, good, really did not know that this function existed in Javascript, but I already knew the NaN that would be if I’m not mistaken Not Assigned Number how about you increase your response with the explanation of NaN ? I could mark it as right, because it was better than mine :)

  • 2

    Remembering that !isNaN('Infinity') -> true

  • How so Infinity? also did not know this, aiai javascript...

  • 1

    isNaN in javascript means: is not a number (not a number)

  • 1

    Remembering that isNaN will return true to strings that can be converted to numbers ;) i.e.: isNaN("0.5") results in false results. But "0.5" === 0.5 is not true.

  • is true @Renan however if you see from the point of view of the question, which is about how to know if the variable is the Tipo javascript number, it would be correct not to use isNan would not be?

  • If you just want to check the typing of the variable it has to be with typeof same. The isNaN is to check if it is not a number for javascript, regardless of type.

  • @Renan isNaN('0.5') returns false because Number('0.5') === 0.5 is true or + '0.5' === 0.5

Show 5 more comments

6

I use the function isNaN, that checks if the variable is not a number and denies it.

var valor = 1.5;
var teste = "a";

console.log(!isNaN(valor)); /* retorna false negando fica true, 1.5 é tipo numérico */
console.log(!isNaN(teste)); /* retorna true negando fica falso, "a" não é um número */
  1. http://msdn.microsoft.com/pt-br/library/66ztdbe6(v=vs.94). aspx

UPDATE

You can also convert:

var valor = 1.5;
var teste = "a";
console.log(!!+valor); // é um número
console.log(!!+teste); // não é numero

The + operator in front of the variable tries to convert the variable to number. If it does not give it returns Nan (false), denying twice to get the correct result: false (not number).

  • unfortunately already posted an answer on isNaN but I’ll give you +1 for the effort, thank you! :)

  • 1

    Actually when they posted I was just typing! It’s okay we’re here to learn, the important thing is that you understand how it works!

  • @Pauloroberto all correct answers should receive +1. This is not the Highlander series.

  • @Laerte only lembando that isNaN considers strings that can be transformed into numbers as numbers themselves. For example, "0.5" is different from 0.5, but isNaN("0.5") results in false.

  • but of course I did, because you think I gave him +1. it was for the effort and being right :}

4

  • Interesting, Regex is the best thing I’ve ever seen in my life.

  • 5

    Not half a cannonball to kill a fly?

3

You refer to checking the type of the value or only if it is numerical?

If you want to know if it is numerical you can check with a regular expression.

The case below accepts the "float" format so to speak, but can be easily adapted to integers or to comma to point fillings:

function isNumeric(value) {

    return /^\d+(?:\.\d+)?$/.test(value);

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.