How to check if a variable is float, decimal or integer in JavaScript? [duplicate]

7

I tried with typeof() , but it only returns me if it's a number, string , etc.

It would look something like this:

var x = 1.2;

if (x == inteiro){
    alert("x é um inteiro");
}
    
asked by anonymous 14.11.2015 / 20:28

2 answers

11

According to MDN documentation there are a few types . The numeric type does not distinguish whether it is integer, decimal, or have binary decimal point. Then you can not get this information. And in general this is irrelevant.

typeof documentation makes it clear what the returns possible.

undefined
boolean
number
string
symbol
function
object
Outros dependendo da implementação do JavaScript.

What you can do is check whether a value has a decimal part or not, by taking the rest:

var x = 1.2;
if (x % 1 === 0){
  document.body.innerHTML += "x é um inteiro";
}
var y = 10;
if (y % 1 === 0){
  document.body.innerHTML += "y é um inteiro";
}

In version 6 in EcmaScript, which few browsers still support, you can use Number.isInteger() . It can be simulated like this:

Number.isInteger = Number.isInteger || function(value) {
    return typeof value === "number" && 
           isFinite(value) && 
           Math.floor(value) === value;
};
    
14.11.2015 / 20:48
7

Here's a suggestion, to give you an idea of how you could do it:

// string, float, decimal ou inteiro em javascript
function tipo(nr) {
    if (typeof nr == 'string' && nr.match(/(\d+[,.]\d+)/)) return 'string decimal';
    else if (typeof nr == 'string' && nr.match(/(\d+)/)) return 'string inteiro';
    else if (typeof nr == 'number') return nr % 1 == 0 ? 'numero inteiro' : 'numero decimal';
    else return false;
}

var testes = [10, 5.5, '10', '5.5', 'virus'].map(tipo);
console.log(testes);
// dá: ["numero inteiro", "numero decimal", "string inteiro", "string decimal", false]

jsFiddle: link

In the background checks whether it is of type String or Number and if it is decimal or integer. In the regex I put comma and dot as an option, but you can remove one if you are sure of the strings you are going to receive.

    
14.11.2015 / 21:43