How to check if a number is decimal?

8

Is there a way to tell if a number is a decimal, that is, if it contains a "comma"?;

A code I found was this:

Html

   <input type="text" onblur="isNumber(this.value)" id="text" />

JavaScript

 function isNumber(text){  
     valor = parseFloat(text);  
     if ((!isNaN(valor))==false){
        alert("Por favor, não digite ...");}  
     return true;  
  }  

Via: link

But it is not working. To see how it went here

To summarize, I only want a condition that returns

true to: 5.69541 e

false to: 569 .

Thank you.

    
asked by anonymous 05.08.2014 / 22:45

2 answers

9

If your number is in text format, the most guaranteed way to determine whether or not it is decimal is through a regex:

texto.match(/^-?\d+\.\d+$/);

That's because using only parseInt and parseFloat is not enough - text can start with a number and contain other things later:

parseInt("123abc");     // 123
parseFloat("123.4abc"); // 123.4

If your number is already in Number format, on the other hand, you can determine whether it is decimal by calculating the rest of the division by 1 :

x % 1 != 0 && !isNaN(x % 1) // true se e somente se x é decimal

Integer numbers always return zero as the remainder of the division by 1, while fractional numbers return a nonzero value. NaN and Infinity return NaN .

    
06.08.2014 / 00:47
8

If I understand correctly, you want a function that returns false for integers and non-numeric values, and true for broken numbers.

Something like this should work:

function isDecimal(num) {
    if(isNaN(num)) return false;             // false para não numéricos
    return parseInt(num) != parseFloat(num); // false para inteiros
}

Numbers must be passed with a dot as a separator, not a comma. Oh, and throw away the code you found on the internet. It's rubbish, it has at least 2 problems in 4 lines ... At least the site owner admits that there is something bad there:)

As requested, the same code rewritten using keys in if :

function isDecimal(num) {
    if(isNaN(num)) { return false; }
    return parseInt(num) != parseFloat(num);
}

Or:

function isDecimal(num) {
    if(isNaN(num)) { 
        return false; 
    } else {
        return parseInt(num) != parseFloat(num);
    }
}

Or:

function isDecimal(num) {
    return (parseInt(num) != parseFloat(num)) && !isNaN(num);
}
    
05.08.2014 / 23:24