How to check if a number is decimal?

Asked

Viewed 6,234 times

10

Is there any way to know if a number is decimal, ie if it contains "comma"?;

One 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: http://scriptsexemplos.blogspot.com.br/2011/04/validar-se-um-numero-e-decimal.html

But it’s not working. To see how was click here

To summarize, I just want a condition that returns

true for: 5.69541 and

false for: 569.

Thank you.

2 answers

12


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

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

That’s because I only use parseInt and parseFloat not enough - the text can get started with a number and contain other things afterwards:

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

If your number is already in format Number, on the other hand, one 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

Integers always return zero as the rest of the division by 1, while fractional numbers return a non-zero value. NaN and Infinity return NaN.

  • 1

    Your last line of code solves the whole problem in a more elegant way than my solution.

  • One thing I never understood until today are these mixed symbols (/^-?\d+\.\d+$/), that you called regex. I will search and understand your reply @mgibsonbr. But it sounds great.

  • 4

    @Samirbraga Even search, because regular expressions (regular Expressions - RegExp or simply regex) are a powerful yet often misused tool. My expression above says: ^ string start, -? with or without less at the front, \d+ one or more digits, \. dot, \d+ one or more digits, $ end of string.

  • 1

    And another, your regex solution is much faster than mine: http://jsperf.com/regex-versus-parseint-float-isnan. @Samirbraga, you should accept this answer instead of mine...

  • @bfavaretto No V8 (Chrome, Opera), yes, but in Firefox and Safari yours is faster. Regex is not usually something efficient... But in that case, it is necessary (the parseFloat suffers from the numeric prefix problem and any suffix, as mentioned in the answer).

  • I like the solution with regex because it’s much simpler. I needed the isNaN to eliminate the suffixes parseint/float passes, and other non-numerical values.

Show 1 more comment

9

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

Something like that should work:

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

The numbers need to be passed with a dot as a separator, not a comma. Ah, and throw away the code you found on the internet. It is a garbage, has at least 2 problems in 4 lines... At least the owner of the site admits that there is bad thing there :)


As requested, the same code rewritten using keys in the 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 else:

function isDecimal(num) {
    return (parseInt(num) != parseFloat(num)) && !isNaN(num);
}
  • You could put your example in the simple structure of if , ie with keys({ }), so that I can adapt to my case. Sorry my ignorance, is that I’m still starting.

  • Okay. As you are starting out, be sure to do what I said in the comment above: always test your code with the browser console open (F12), even in jsfiddle. Several errors are shown in red, and are key information for you to post when asking something here on the site.

  • Thank you for the edition in your reply, I was able to test with my example, and I noticed that your code differs the numbers from the other values, such as words, but it returns true both for decimal numbers (5.66, with dot), and for integers(566). Not differing them.

  • Are you sure, @Samirbraga? My tests give different results http://jsfiddle.net/V52p4/

  • Now with his example I could realize that I was performing the function incorrectly. Thank you for your reply, it truly helped me.

Browser other questions tagged

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