How do I know if a variable is of type Number in JavaScript?

18

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

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

How is this possible?

    
asked by anonymous 04.02.2014 / 16:47

7 answers

15

It is simple to know if a variable is Numero or not because there is a native Javascript operator that says the type of your variable, which would be the typeof operator, 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 is an example of a function that checks whether the type is number

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

Testing all the values that I have exemplified above, you will see that only those with type number that 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 as simple as that.

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

    
04.02.2014 / 16:47
9

If you are not looking to verify that something is a number, but rather behaves like , you 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 an response from the OS by CMS .

    
04.02.2014 / 17:02
8

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 tried to go the way of finding out if a particular variable "represents" a number; a fairly common problem, and a task that may not be as easy in JavaScript (as in most dynamic languages).

While I may be extrapolating the question, since Paul did not mention this point or tagged libraries in the question. I think it's fair to point out that the infamous jQuery has jQuery.isNumeric () itself to solve this second problem of types that may behave like (or be converted to) numbers. When writing regular expressions or combinations of methods isXXX , I think it is worth using the library, avoiding the various puzzles of the language:

Documentation examples:

$.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
    
04.02.2014 / 17:43
7

Javascript has a native function to check if it is not numeric by testing it along with the weak type isNaN .

So if you want to know if it is numeric you can use !isNaN and it will return true for 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

Conditional use example:

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

What a compact way to write this:

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
}

To not include the value Infinity that is native and can be represented by a string, you can combine it with the isFinite function, eg:

!isNaN(numero) && isFinite(numero); // Se for número e não for Infinity vai retornar true
    
04.02.2014 / 16:53
5

I use the isNaN function, which checks that the variable is not a number and deny 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 */
  • link
  • 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 it twice to get the correct result: false (not number).

        
    04.02.2014 / 16:58
    3

    The function below tests with regular expression the string passed as parameter and returns true on positive (string is a number) or false.

    function isNumeric(str) {  
         var er = /^[0-9]+$/;  
         return (er.test(str));
    } 
    

    source: link

        
    04.02.2014 / 16:50
    2

    Do you mean to check the value type or only if it is numeric?

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

    The below case accepts the float format so to speak, but can be easily adapted for integers or comma to the underside of dot:

    function isNumeric(value) {
    
        return /^\d+(?:\.\d+)?$/.test(value);
    
    }
    
        
    04.02.2014 / 17:50