¿Cómo convertir NaN de parseInt en 0 para una cadena vacía?


¿Es posible de alguna manera devolver 0 en lugar de NaN al analizar valores en JavaScript?

En el caso de la cadena vacía parseInt devuelve NaN.

Es posible hacer algo así en JavaScript para comprobar NaN?

var value = parseInt(tbb) == NaN ? 0 : parseInt(tbb)

O tal vez hay otra función o plugin jQuery que puede hacer algo similar?

Author: Xufox, 2011-07-18

16 answers

var s = '';

var num = parseInt(s) || 0;
 609
Author: Matthew Caruana Galizia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-18 17:02:31

También puedes usar la función isNaN():

var s = ''
var num = isNaN(parseInt(s)) ? 0 : parseInt(s)
 43
Author: gprasant,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-25 09:16:42

Me sorprendió no ver a nadie mencionar el uso de Number(). Granted analizará decimales si se proporciona, por lo que actuará de manera diferente a parseInt(), sin embargo, ya asume la base 10 y cambiará "" o incluso "" a 0.

 19
Author: Chris Werner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-13 10:17:07

Para las personas que no están restringidas a parseInt, puede usar el operador OR bitwise (que implícitamente llama ToInt32 a sus operandos).

var value = s | 0;

// NaN | 0     ==>> 0
// ''  | 0     ==>> 0
// '5' | 0     ==>> 5
// '33Ab' | 0  ==>> 0
// '0x23' | 0  ==>> 35
// 113 | 0     ==>> 113
// -12 | 0     ==>> -12
// 3.9 | 0     ==>> 3

Nota: ToInt32 es diferente de parseInt. (es decir, parseInt('33Ab') === 33)

 7
Author: Ahmad Ibrahim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-13 17:49:00

El problema

Otras respuestas no toman en cuenta que 0 es falso, y por lo tanto lo siguiente será 20 en lugar de 0:

var myNumber = parseInt('0') || 20; // 20

La solución

Propongo una función auxiliar, que resuelve la mayoría de los problemas:

function getNumber(number, defaultNumber) {
    return isNaN(parseInt(number, 10)) ? defaultNumber : parseInt(number, 10);
}

La función helper dará los siguientes resultados:

getNumber('0', 20); // 0
getNumber('2', 20); // 2
getNumber('2.2', 20); // 2
getNumber('any string', 20); // 20
getNumber(undefined, 20); // 20
getNumber(null, 20); // 20
getNumber(NaN, 20); // 20
getNumber(false, 20); // 20
getNumber(true, 20); // 20
 3
Author: sqren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-05 21:59:32
var value = isNaN(parseInt(tbb)) ? 0 : parseInt(tbb);
 2
Author: Milap Jethwa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-23 20:28:40

Haga una comprobación por separado para una cadena vacía ( ya que es un caso específico ) y póngala a cero en este caso.

Puede aparecer y "0" al principio, pero luego debe agregar un prefijo para indicar que es un decimal y no un número octal

 1
Author: Schroedingers Cat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-18 17:01:08

¿Por qué no sobrescribir la función? En ese caso, siempre puede estar seguro de que devuelve 0 en el caso de NaN:

(function(original) {
    parseInt = function() {
        return original.apply(window, arguments) || 0;
    };
})(parseInt);

Ahora, en cualquier lugar de tu código:

parseInt('') === 0
 1
Author: pimvdb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-10-23 17:56:56

Tuve un problema similar (firefox v34) con cadenas simples como:

var myInt = parseInt("b4");

Así que se me ocurrió un truco rápido de:

var intVal = ("" + val).replace(/[^0-9]/gi, "");

Y luego se complicó todo estúpido para tratar con flotadores + ints para cosas no simples:

var myval = "12.34";

function slowParseNumber(val, asInt){
    var ret = Number( ("" + val).replace(/[^0-9\.]/gi, "") );
    return asInt ? Math.floor(ret) : ret;
}
var floatVal = slowParseNumber(myval);

var intVal = slowParseNumber(myval, true);
console.log(floatVal, intVal);

Devolverá 0 para cosas como:

var intVal = slowParseNumber("b"); // yeilds 0
 1
Author: bob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-04 09:54:33
//////////////////////////////////////////////////////
function ToInt(x){x=parseInt(x);return isNaN(x)?0:x;}
//////////////////////////////////////////////////////
var x = ToInt('');   //->  x=0
    x = ToInt('abc') //->  x=0
    x = ToInt('0.1') //->  x=0
    x = ToInt('5.9') //->  x=5
    x = ToInt(5.9)   //->  x=5
    x = ToInt(5)     //->  x=5
 1
Author: AbdulRahman AlShamiri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-13 20:03:29

Hace el trabajo mucho más limpio que parseInt en mi opinión, Use el operador +

var s = '';
console.log(+s);

var s = '1024'
+s
1024

s = 0
+s
0

s = -1
+s
-1

s = 2.456
+s
2.456

s = ''
+s
0

s = 'wtf'
+s
NaN
 1
Author: PirateApp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-02 06:03:40
// implicit cast
var value = parseInt(tbb*1); // see original question

Explicación, para aquellos que no lo encuentran trivial:

Multiplicando por uno, un método llamado "implicit cast", intenta convertir el operando de tipo desconocido en el tipo primitivo 'number'. En particular, una cadena vacía se convertiría en el número 0, convirtiéndola en un tipo elegible para parseInt()...

Un muy buen ejemplo también fue dado anteriormente por PirateApp, quien sugirió anteponer el signo+, forzando a JavaScript a usar el Número implicit cast.

 1
Author: Fabien Haddadi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-16 11:40:28

También de esta manera, por qué no escribir una función y llamarla donde sea necesario . Asumo que es la entrada en los campos del formulario para realizar cálculos.

var Nanprocessor = function (entry) {
    if(entry=="NaN") {
        return 0;
    } else {
        return entry;
    }
}

 outputfield.value = Nanprocessor(x); 

// where x is a value that is collected from a from field
// i.e say x =parseInt(formfield1.value); 

¿Qué está mal haciendo esto?

 0
Author: Naresh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-10 12:27:14

Aquí hay un método tryParseInt que estoy usando, este toma el valor predeterminado como segundo parámetro para que pueda ser cualquier cosa que necesite.

function tryParseInt(str, defaultValue) {
    return parseInt(str) == str ? parseInt(str) : defaultValue;
}

tryParseInt("", 0);//0 
tryParseInt("string", 0);//0 
tryParseInt("558", 0);//558
 0
Author: Darrelk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-12 12:07:13

Creé un prototipo de 2 para manejar esto por mí, uno para un número y uno para una cadena.

// This is a safety check to make sure the prototype is not already defined.
Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
};

// returns the int value or -1 by default if it fails
Number.method('tryParseInt', function (defaultValue) {
    return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});

// returns the int value or -1 by default if it fails
String.method('tryParseInt', function (defaultValue) {
    return parseInt(this) == this ? parseInt(this) : (defaultValue === undefined ? -1 : defaultValue);
});

Si no desea utilizar el control de seguridad, utilice

String.prototype.tryParseInt = function(){
    /*Method body here*/
};
Number.prototype.tryParseInt = function(){
     /*Method body here*/
};

Ejemplo de uso:

var test = 1;
console.log(test.tryParseInt()); // returns 1

var test2 = '1';
console.log(test2.tryParseInt()); // returns 1

var test3 = '1a';
console.log(test3.tryParseInt()); // returns -1 as that is the default

var test4 = '1a';
console.log(test4.tryParseInt(0));// returns 0, the specified default value
 0
Author: Mike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-05 15:19:02

Una función auxiliar que todavía permite usar la raíz

function parseIntWithFallback(s, fallback, radix) {
    var parsed = parseInt(s, radix);
    return isNaN(parsed) ? fallback : parsed;
}
 0
Author: Jerome Diaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-03 14:27:06