Videos
parseInt("123qwe")
returns 123
Number("123qwe")
returns NaN
In other words parseInt() parses up to the first non-digit and returns whatever it had parsed. Number() wants to convert the entire string into a number, which can also be a float BTW.
EDIT #1: Lucero commented about the radix that can be used along with parseInt(). As far as that is concerned, please see THE DOCTOR's answer below (I'm not going to copy that here, the doc shall have a fair share of the fame...).
EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number() in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat() aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui") also returns NaN). And the biggest difference is the use of radix that Number() doesn't know of and parseInt() may indirectly guess from the given string (that can cause weird results sometimes).
The first one takes two parameters:
parseInt(string, radix)
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
- If the string begins with "0x", the
radix is 16 (hexadecimal) - If the string begins with "0", the
radix is 8 (octal). This feature
is deprecated - If the string begins with any other value, the radix is 10 (decimal)
The other function you mentioned takes only one parameter:
Number(object)
The Number() function converts the object argument to a number that represents the object's value.
If the value cannot be converted to a legal number, NaN is returned.
parseInt() es una función de alto nivel que sirve para parsear una cadena e intentar obtener un valor numérico a partir de esta.
Por intentar me refiero lo sgte:
Una cadena que evidentemente es un número, es fácilmente obtenible como number. Ejemplo:
var s = "1234";
var n = parseInt(s);
console.log(n); // 1234
Por supuesto también acepta negativos
var s = "-1234";
var n = parseInt(s);
console.log(n); // -1234
Sin embargo una cadena que no represente a un número como la sgte
var s = "5678EstoYaNoEsNumero";
var n = parseInt(s);
console.log(n); // 5678
Igualmente obtiene un valor válido, que corresponde al número resultante de convertir a number los dígitos hasta donde se pudo.
Este comportamiento resulta ideal por ejemplo en campos de texto cuando pueden haber espacios en blanco antes o después ejemplo:
var s = " 4321 ";
var n = parseInt(s);
console.log(n); // 4321
Cuando el parseo ya no puede obtener ningún número, este se detiene así hayan más dígitos posteriormente por lo que en este caso el parseo devolverá NaN lo que significa que no pudo obtener un valor válido. Ejemplo:
var s = " abc8765 ";
var n = parseInt(s);
console.log(n); // NaN
Pero no solo permite parsear cadenas en base 10 por ejemplo lo sgte también es válido en base hexadecimal
var sHexa = "0xDEAD";
var nHexa = parseInt(sHexa);
console.log(nHexa); // 57005
Finalmente si se desea parsear una cadena en otra base se puede indicar con el segundo argumento de la función, por ejemplo para parsear una cadena binaria:
var sBin = "10101010";
var nBin = parseInt(sBin, 2);
console.log(nBin); // 170
¿Qué es el parseInt y para qué sirve en programación?
parseInt lo que hace es analizar una cadena de texto y retornar el valor numérico.
Cuando nosotros escribimos en el teclado algún número (ej 123), el teclado envía un conjunto de carácteres codificados por cada tecla enviada (comúnmente en ascii), así
la cadena de carácteres 1 2 3 es representado internamente como 0x31 0x32 0x33. Por otro lado 123 como número debe representarse internamente como 0x7B
Entonces parseInt transforma los bytes 0x31 0x32 0x33 en 0x7B
function analizarEntero(cadena)
{
var r = 0
for(var i = 0; i < cadena.length; i++)
{
var c = cadena.charCodeAt(i) - 0x30
if(c < 0 || c > 9)
throw new Error("Se esperan sólo dígitos")
r = r * 10 + c
}
return r
}
console.log(analizarEntero('1230'))
El anterior código muestra como convertir una cadena a un entero, primero se convierte el ascii a un dígito válido (0-9), se desplaza a la izquierda el acumulador (en nuestro sistema esto se hace multiplicando por 10) finalmente se suma el dígito, repetir hasta que no queden caracteres.
Number.parseInt(string, radix) hace algo parecido, pero él acepta más sistemas de númeración con sus respectivos símbolos
console.log(Number.parseInt('F', 16)) // 15 en hex
console.log(Number.parseInt('15', 10)) // 15 en decimal
console.log(Number.parseInt('17', 8)) // 15 en octal
console.log(Number.parseInt('1111', 2)) // 15 en binario