Check if string has only numbers

4

What command can I use to know if a string contains only numbers?

For example, I'm using prompt :

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

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

    
asked by anonymous 01.04.2014 / 16:46

4 answers

15

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's 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;
}
    
01.04.2014 / 16:53
2

Use isNaN to know if the string contains only numbers, if false it means 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
    
01.04.2014 / 16:51
1

See if this helps:

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

You can test the String with a regular expression:

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

Being '0' is the number received in the String.

If you want to accept broken numbers, it might look 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 two ways:

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

E:

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

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

$.isNumeric('0');
    
01.04.2014 / 16:52