🌐
MDN Web Docs
developer.mozilla.org › es › docs › Web › JavaScript › Reference › Global_Objects › parseInt
parseInt() - JavaScript | MDN
La función parseInt comprueba el primer argumento, una cadena, e intenta devolver un entero de la base especificada. Por ejemplo, una base de 10 indica una conversión a número decimal, 8 octal, 16 hexadecimal, y así sucesivamente. Para bases superiores a 10, las letras del alfabeto indican ...
🌐
MDN Web Docs
developer.mozilla.org › es › docs › Web › JavaScript › Reference › Global_Objects › Number › parseInt
Number.parseInt() - JavaScript | MDN
El método estático Number.parseInt() analiza un argumento de cadena y devuelve un número entero de la raíz o base especificada.
🌐
W3Schools
w3schools.com › jsref › jsref_parseint.asp
JavaScript parseInt() Method
The parseInt method parses a value as a string and returns the first integer. A radix parameter specifies the number system to use: 2 = binary, 8 = octal, 10 = decimal, 16 = hexadecimal. If radix is omitted, JavaScript assumes radix 10.
🌐
Vultr Docs
docs.vultr.com › javascript › global › parseInt
JavaScript parseInt() - Parse String to Integer | Vultr Docs
September 30, 2024 - The parseInt() function in JavaScript is a fundamental utility used to convert strings into integers. This method proves invaluable when you need to extract numbers from text data, or when handling inputs that should be integers for mathematical ...
🌐
Codecademy
codecademy.com › docs › javascript › number methods › .parseint()
JavaScript | Number Methods | .parseInt() | Codecademy
May 31, 2024 - In JavaScript, the .parseInt() function converts a string into an integer. This function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
🌐
Programiz
programiz.com › javascript › library › built-in › parseInt
JavaScript parseInt()
Created with over a decade of ... a certified JavaScript programmer. Try Programiz PRO! ... The parseInt() function parses a string argument and returns an integer of the specified radix....
🌐
DEV Community
dev.to › judevector › understanding-parseint-in-javascript-usage-quirks-and-best-practices-1dl7
Understanding parseInt in JavaScript: Usage, Quirks, and Best Practices - DEV Community
October 5, 2023 - In JavaScript, the radix can range from 2 to 36. Specifying a radix is crucial because it ensures consistent behaviour across different environments. Without specifying a radix, parseInt could interpret the string as octal, decimal, or hexadecimal based on its content, which could lead to ...
🌐
freeCodeCamp
freecodecamp.org › news › parseint-in-javascript-js-string-to-int-example
parseInt() in JavaScript – JS String to Int Example
February 11, 2022 - In this tutorial, we will talk about the parseInt function in JavaScript. This function parses (break down) a string and returns an integer or NaN (Not a Number). How the parseInt function works The main purpose of using the parseInt function ...
🌐
DEV Community
dev.to › ussdlover › understanding-parseint-in-javascript-4a24
Understanding parseInt() in JavaScript - DEV Community
July 29, 2023 - Understanding the parseInt() function and the radix parameter is crucial when working with string-to-integer conversions in JavaScript. Always include the radix parameter to ensure consistent and predictable results, especially when dealing with numbers that start with '0'. This knowledge will ...
Find elsewhere
🌐
W3Schools
w3schools.com › jsref_parseint.asp
JavaScript parseInt() Function
The parseInt() function parses a string and returns an integer. 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 ...
🌐
Scaler
scaler.com › home › topics › parseint() in javascript
ParseInt() in JavaScript - Scaler Topics
January 1, 2024 - The JavaScript parseInt() function is a built-in function that is used to parse a string argument to return the first integer. The number system to use is specified by a radix parameter.
🌐
Tabnine
tabnine.com › home › how to use parseint() in javascript
How to Use parseInt() in JavaScript - Tabnine
July 25, 2024 - When parseInt() reaches a character that is not numeral in the specified radix, it stops reading the string and returns the integer value parsed up to that point. For radices above 10, letters of the English alphabet indicate numerals greater than 9. For example, when using base 16 (hexadecimal numbers) ‘A’ through ‘F’ are used (A = 10, F = 15).
🌐
Code.mu
code.mu › en › javascript › manual › lang › parseInt
The parseInt function - a string to an integer conversion in JavaScript
The parseInt function converts a string to an integer. This is necessary for values like '12px' - when first there is a number, and then units of measurement. If you apply the parseInt function to '12px', then the result will be the number 12 (and it will really be a number, not a string).
🌐
TechOnTheNet
techonthenet.com › js › number_parseint.php
JavaScript: Number parseInt() method
In JavaScript, parseInt() is a Number method that is used to parse a string and return its value as an integer number.
🌐
HCL Software
help.hcl-software.com › dom_designer › 9.0.1 › reference › r_wpdr_elements_tlfunctions_parseint_r.html
parseInt (JavaScript)
See isNaN (JavaScript). This example creates integers from strings in radix 10, 8, and 16, and tests them to make sure they are valid numbers. function p(stuff) { print("<<<" + stuff + ">>>"); } var i = parseInt("25"); if (isNaN(i)) p("i is not a number"); else p("i = " + i); // i = 25 var i = parseInt("25", 8); if (isNaN(i)) p("i is not a number"); else p("i = " + i); // i = 21 var i = parseInt("25", 16); if (isNaN(i)) p("i is not a number"); else p("i = " + i); // i = 37 var i = parseInt("25x"); if (isNaN(i)) p("i is not a number"); else p("i = " + i); // i is not a number var i = parseInt("ff", 16); if (isNaN(i)) p("i is not a number"); else p("i = " + i); // i = 255
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Basic JavaScript - Use the parseInt Function - JavaScript - The freeCodeCamp Forum
December 20, 2022 - Just add code to it without erasing anything · The parseInt() method takes an argument. If a argument passed is a string and a number i.e.parseInt("56"); It will return integer 56. And if a argument passed is a string and not a number i.e. ...
🌐
SheCodes
shecodes.io › athena › 60744-what-is-parseint-in-javascript
[JavaScript] - What is parseInt() in JavaScript? - SheCodes | SheCodes
Learn about the parseInt() function in JavaScript and how it converts a string argument to an integer of a specified radix.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-number-parseint-method
JavaScript Number parseInt() Method - GeeksforGeeks
July 25, 2018 - The parseInt() method parses a value by converting it to a string and returns the first integer found. It also accepts an optional radix parameter that specifies the base of the numeral system.
Top answer
1 of 6
425
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).

2 of 6
91

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.

Top answer
1 of 4
18

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

2 of 4
6

¿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