How to verify if a variable is float, decimal or integer in Javascript?

Asked

Viewed 8,942 times

11

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

It would be something like that:

var x = 1.2;

if (x == inteiro){
    alert("x é um inteiro");
}
  • 1

    Obviously the questions are not duplicates, just read them.

2 answers

16


According to the MDN documentation there are few types. The numeric type makes no distinction whether it is integer, decimal or has binary decimal point. So there is no way to obtain this information. And by and large this is irrelevant.

To documentation of typeof makes clear which returns possible.

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

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

var x = 1.2;
if (x % 1 === 0) console.log("x é um inteiro");
var y = 10;
if (y % 1 === 0) console.log("y é um inteiro");

I put in the Github for future reference.

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

Number.isInteger = Number.isInteger || function(value) {
    return typeof value === "number" && 
           isFinite(value) && 
           Math.floor(value) === value;
};
  • Really, from what I checked there is no way to do such a condition in an easy way by checking if it is a float, double variable. I just wanted to know if I could do it. But thank you so much for the answer :D

  • I’m a beginner in the stack, then I’m getting beaten to touch it still kkk.

9

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: http://jsfiddle.net/w6rtg24v/2

In the background check if it’s the type String or Number and if it is decimal or integer. In regex I put comma and dot as option, but you can remove one of them if you are sure of the strings you will receive.

Browser other questions tagged

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