Check if string has only numbers

Asked

Viewed 43,355 times

4

Which command can I use to know if inside a string only has numbers..

For example, I’m using the prompt:

var quantidade=prompt('Quantidade de entrada de produtos(somente números)');

I would like to check if really in the variable quantidade has only numbers, after all we can not trust these users is not rs.

  • 3
  • 1

    That’s why I said "related" and not "duplicated". It turns out that several answers of that question serve for this, including several answers of this are the same as there.

4 answers

18


Option 1 (Javascript only):

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

isNumber('123'); // true
isNumber('asda123'); // false

Option 2 (using jQuery):

$.isNumeric('123'); // true
$.isNumeric('asdasd123'); // false

As a curiosity, here is the implementation of isNumeric in jQuery 1.11.0:

isNumeric: function( obj ) {
    // parseFloat NaNs numeric-cast false positives (null|true|false|"")
    // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
    // subtraction forces infinities to NaN
    return obj - parseFloat( obj ) >= 0;
}

4

Use isNaN to know if the string contains only numbers, if false means it is a number:

if(!isNaN(num)) alert("a variavel num é numérica");

isNaN(123)         // false, então é numerico
isNaN('123')       // false então só contém numeros
isNaN('teste')     // verdadeiro, não contém números
isNaN('999teste')  // vardadeiro, contém números e letras
  • In fact, the inNaN checks if the value is a number. In this case, if something like 1.23 or 3-2, he will return true. Which doesn’t seem to be the case, since he wants an amount.

  • @Juliopradera does not check if it is numerical, if so, isNaN(123) would return true and not false. What the function does is to check if there are any characters other than numbers, in the case isNaN(123) returns "Nan", that is, there are no characters other than numbers.

  • @Felipe Take the test. Put "1.23" inside a inNaN and you will see that it returns false. For "1.23" is a number. But it does not contain only numbers.

  • @Júliopradera is not saying otherwise. The example solves the problem, since it requires only numbers, according to the author.

1

See if it helps you:

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

1

You can test String with a regular expression:

/^\d+$/.test('0'); // Retorna true.

Whereas '0' is the number received in String.

If you want to accept broken numbers she can be like this:

/^\d+(?:\.\d+)?$/.test('0.1'); // Retorna true.

You can also create a function to reuse like this:

var

    isNumeric = function(value) {

        return /^\d+(?:\.\d+)?$/.test(value);

    };

String.prototype.isNumeric = function() {

    return isNumeric(this);

};

So you can use it in these two ways:

isNumeric('0'); // Retorna true.

And:

'0.1'.isNumeric(); // Retorna true.

With jQuery already exists a function (jQuery.fn.isNumeric):

$.isNumeric('0');

Browser other questions tagged

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