Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

parseInt()

Esta tradução está incompleta. Ajude atraduzir este artigo.

Sumário

A função parseInt() analisa um argumento string e retorna um inteiro da raíz ou base especificada.

Sintaxe

parseInt(string, radix);

Parâmetros

string

O valor a analisar. Se string não for uma string, então o valor é convertido para uma. Os espaços em branco na string são ignorados.

radix
Um inteiro que representa a raíz da string mencionada no parâmetro anterior. Sempre especifique este parâmetro para eliminar confusão do leitor e para garantir o comportamento esperado. Implementações diferentes produzem resultados diferentes quando radix não é especificado.

Description

The parseInt function converts its first argument to a string, parses it, and returns an integer or NaN. If not NaN, the returned value will be the decimal integer representation of the first argument taken as a number in the specified radix (base). For example, a radix of 10 indicates to convert from a decimal number, 8 octal, 16 hexadecimal, and so on. For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.

If radix is undefined or 0 (or absent), JavaScript assumes the following:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal).  Exactly which radix is chosen is implementation-dependent.  ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.  For this reason always specify a radix when using parseInt.
  • If the input string begins with any other value, the radix is 10 (decimal).

If the first character cannot be converted to a number, parseInt returns NaN.

For arithmetic purposes, the NaN value is not a number in any radix. You can call the isNaN function to determine if the result of parseInt is NaN. If NaN is passed on to arithmetic operations, the operation results will also be NaN.

To convert number to its string literal in a particular radix use intValue.toString(radix).

Examples

Example: Using parseInt

The following examples all return 15:

parseInt(" 0xF", 16);
parseInt(" F", 16);
parseInt("17", 8);
parseInt(021, 8);
parseInt("015", 10);
parseInt(15.99, 10);
parseInt("FXX123", 16);
parseInt("1111", 2);
parseInt("15*3", 10);
parseInt("15e2", 10);
parseInt("15px", 10);
parseInt("12", 13);

The following examples all return NaN:

parseInt("Hello", 8); // Not a number at all
parseInt("546", 2);   // Digits are not valid for binary representations

The following examples all return -15:

parseInt("-F", 16);
parseInt("-0F", 16);
parseInt("-0XF", 16);
parseInt(-15.1, 10)
parseInt(" -17", 8);
parseInt(" -15", 10);
parseInt("-1111", 2);
parseInt("-15e1", 10);
parseInt("-12", 13);

The following example returns 224:

parseInt("0e0", 16);

Octal interpretations with no radix

Although discouraged by ECMAScript 3 and forbidden by ECMAScript 5, many implementations interpret a numeric string beginning with a leading 0 as octal. The following may have an octal result, or it may have a decimal result.  Always specify a radix to avoid this unreliable behavior.

parseInt("0e0"); // 0
parseInt("08"); // 0, '8' is not an octal digit.

ECMAScript 5 removes octal interpretation

The ECMAScript 5 specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values. ECMAScript 5 states:

The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading white space in string is ignored. If radix is undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix of 16 is assumed. If radix is 16, number may also optionally begin with the character pairs 0x or 0X.

This differs from ECMAScript 3, which discouraged but allowed octal interpretation.

Many implementations have not adopted this behavior as of 2013, and because older browsers must be supported, always specify a radix.

A stricter parse function

É útil em algum momento ter uma maneira mais rigorosa para analisar valores int, expressões regulares podem ajudar:

filterInt = function (value) {
  if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
    return Number(value);
  return NaN;
}

console.log(filterInt('421'));               // 421
console.log(filterInt('-421'));              // -421
console.log(filterInt('+421'));              // 421
console.log(filterInt('Infinity'));          // Infinity
console.log(filterInt('421e+0'));            // NaN
console.log(filterInt('421hop'));            // NaN
console.log(filterInt('hop1.61803398875'));  // NaN
console.log(filterInt('1.61803398875'));     // NaN

Especificações

Especificação Status Comentário
ECMAScript 1st Edition. Padrão Definição inicial
ECMAScript 5.1 (ECMA-262)
The definition of 'parseInt' in that specification.
Standard  
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'parseInt' in that specification.
Standard  

Compatibilidade de navegador

Característica Chrome Firefox (Gecko) Internet Explorer Opera Safari
Suporte básico (Yes) (Yes) (Yes) (Yes) (Yes)
Característica Android Chrome para Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Suporte básico (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

Veja também

Etiquetas do documento e colaboradores

 Colaboradores desta página: odahcam, SphinxKnight, teoli, oshiroam
 Última atualização por: odahcam,