From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../global_objects/number/epsilon/index.html | 69 +++++++ .../reference/global_objects/number/index.html | 221 +++++++++++++++++++++ .../global_objects/number/isfinite/index.html | 86 ++++++++ .../global_objects/number/isinteger/index.html | 136 +++++++++++++ .../global_objects/number/isnan/index.html | 131 ++++++++++++ .../global_objects/number/issafeinteger/index.html | 104 ++++++++++ .../number/max_safe_integer/index.html | 83 ++++++++ .../global_objects/number/max_value/index.html | 65 ++++++ .../number/min_safe_integer/index.html | 66 ++++++ .../global_objects/number/min_value/index.html | 69 +++++++ .../reference/global_objects/number/nan/index.html | 105 ++++++++++ .../number/negative_infinity/index.html | 84 ++++++++ .../global_objects/number/parsefloat/index.html | 116 +++++++++++ .../global_objects/number/parseint/index.html | 85 ++++++++ .../number/positive_infinity/index.html | 92 +++++++++ .../global_objects/number/prototype/index.html | 139 +++++++++++++ .../global_objects/number/toexponential/index.html | 149 ++++++++++++++ .../global_objects/number/tofixed/index.html | 99 +++++++++ .../number/tolocalestring/index.html | 176 ++++++++++++++++ .../global_objects/number/toprecision/index.html | 104 ++++++++++ .../global_objects/number/tosource/index.html | 48 +++++ .../global_objects/number/tostring/index.html | 143 +++++++++++++ .../global_objects/number/valueof/index.html | 80 ++++++++ 23 files changed, 2450 insertions(+) create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/epsilon/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/isfinite/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/isinteger/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/isnan/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/issafeinteger/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/max_safe_integer/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/max_value/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/min_safe_integer/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/min_value/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/nan/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/negative_infinity/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/parsefloat/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/parseint/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/positive_infinity/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/prototype/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/toexponential/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/tofixed/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/tolocalestring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/toprecision/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/tosource/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/tostring/index.html create mode 100644 files/pt-br/web/javascript/reference/global_objects/number/valueof/index.html (limited to 'files/pt-br/web/javascript/reference/global_objects/number') diff --git a/files/pt-br/web/javascript/reference/global_objects/number/epsilon/index.html b/files/pt-br/web/javascript/reference/global_objects/number/epsilon/index.html new file mode 100644 index 0000000000..bc10fb3285 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/epsilon/index.html @@ -0,0 +1,69 @@ +--- +title: Number.EPSILON +slug: Web/JavaScript/Reference/Global_Objects/Number/EPSILON +tags: + - ECMAScript 2015 + - JavaScript + - Number + - Número + - Property + - Propriedade +translation_of: Web/JavaScript/Reference/Global_Objects/Number/EPSILON +--- +
{{JSRef}}
+ +

A propriedade Number.EPSILON representa a diferença entre 1 e o menor ponto flutuante maior que 1.

+ +

Você não tem que criar um objeto {{jsxref("Number")}} para acessar esta propriedade estática (use Number.EPSILON).

+ +
{{EmbedInteractiveExample("pages/js/number-epsilon.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrição

+ +

A propriedade EPSILON tem o valor de aproximadamente 2.2204460492503130808472633361816E-16, ou 2-52.

+ +

Polyfill

+ +
if (Number.EPSILON === undefined) {
+    Number.EPSILON = Math.pow(2, -52);
+}
+
+ +

Exemplos

+ +

Testando igualdade

+ +
x = 0.2;
+y = 0.3;
+z = 0.1;
+equal = (Math.abs(x - y + z) < Number.EPSILON);
+
+ +

Especificações

+ + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-number.epsilon', 'Number.EPSILON')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.builtins.Number.EPSILON")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/index.html b/files/pt-br/web/javascript/reference/global_objects/number/index.html new file mode 100644 index 0000000000..a21a4264af --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/index.html @@ -0,0 +1,221 @@ +--- +title: Número +slug: Web/JavaScript/Reference/Global_Objects/Number +tags: + - JavaScript + - Número + - Referência(2) +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +
{{JSRef("Global_Objects", "Number")}} 
+ +

Sumário

+ +

O objeto JavaScript Number é um objeto encapsulado que permite você trabalhar com valores numéricos. Um objeto Number é criado utilizando o construtor Number().

+ +

Construtor

+ +
new Number(value);
+ +

Parâmetros

+ +
+
value
+
O valor numérico do objeto sendo criado.
+
+ +

Descrição

+ +

Os principais usos para o objeto Number são:

+ + + +

Propriedades

+ +
+
{{jsxref("Number.EPSILON")}} {{experimental_inline}}
+
O menor intervalo entre dois números representáveis.
+
{{jsxref("Number.MAX_SAFE_INTEGER")}} {{experimental_inline}}
+
O inteiro máximo seguro em JavaScript (253 -1).
+
{{jsxref("Number.MAX_VALUE")}}
+
O maior número representável positivo.
+
{{jsxref("Number.MIN_SAFE_INTEGER")}} {{experimental_inline}}
+
O inteiro mínimo seguro em JavaScript (-(253 -1)).
+
{{jsxref("Number.MIN_VALUE")}}
+
O número mínimo representável positivo - isto é, o número positivo mais próximo de zero (sem ser zero na verdade).
+
{{jsxref("Number.NaN")}}
+
Valor especial que não é número.
+
{{jsxref("Number.NEGATIVE_INFINITY")}}
+
Valor especial representando infinito negativo; retornado no "overflow".
+
{{jsxref("Number.POSITIVE_INFINITY")}}
+
 Valor especial representando infinito; retornado no "overflow".
+
{{jsxref("Number.prototype")}}
+
Permite a adição de propriedades a um objeto Number.
+
+ +
{{jsOverrides("Function", "properties", "MAX_VALUE", "MIN_VALUE", "NaN", "NEGATIVE_INFINITY", "POSITIVE_INFINITY", "protoype")}}
+ +

Methods

+ +
+
{{jsxref("Number.isNaN()")}} {{experimental_inline}}
+
Determina se o valor passado é NaN.
+
{{jsxref("Number.isFinite()")}} {{experimental_inline}}
+
Determina se o tipo e o valor passado é um número finito.
+
{{jsxref("Number.isInteger()")}} {{experimental_inline}}
+
Determina se o tipo do valor passado é  inteiro.
+
{{jsxref("Number.isSafeInteger()")}} {{experimental_inline}}
+
Determina se o tipo do valor passado é um inteiro seguro (número entre -(253 -1) e 253 -1).
+
{{jsxref("Number.toInteger()")}} {{obsolete_inline}}
+
Usado para avaliar o valor passado e convertê-lo a um inteiro (ou infinito), mas foi removido.
+
{{jsxref("Number.parseFloat()")}} {{experimental_inline}}
+
O valor é o mesmo que {{jsxref("Global_Objects/parseFloat", "parseFloat")}} do objeto global.
+
{{jsxref("Number.parseInt()")}} {{experimental_inline}}
+
O valor é o mesmo que {{jsxref("Global_Objects/parseInt", "parseInt")}} do objeto global.
+
+ +
{{jsOverrides("Function", "methods", "isNaN")}}
+ +

Instâncias Number  

+ +

Toda instância Number herdam de {{jsxref("Number.prototype")}}. O objeto 'prototype' do construtor Number pode ser modificado para afetar todas as instâncias Number.

+ +

Métodos

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/prototype', 'Methods')}}
+ +

Exemplos

+ +

Exemplo: Usando o objeto Number para atribuir valores a variáveis numéricas

+ +

O seguinte exemplo usa as propriedades do objeto Number para atribuir valores a várias variáveis numéricas:

+ +
var biggestNum = Number.MAX_VALUE;
+var smallestNum = Number.MIN_VALUE;
+var infiniteNum = Number.POSITIVE_INFINITY;
+var negInfiniteNum = Number.NEGATIVE_INFINITY;
+var notANum = Number.NaN;
+
+ +

Exemplo: Intervalo inteiro para Number

+ +

O seguinte exemplo mostra os valores inteiros mínimo e máximo que podem ser representados como objeto Number (para mais detalhes, referir-se ao padrão EcmaScript standard (EcmaScript standard), capítulo 8.5 O tipo de número (The Number Type):

+ +
var maxInt = 9007199254740992;
+var minInt = -9007199254740992;
+
+ +

Ao analisar dados que foram serializados para JSON, valores inteiros que caem fora desse intervalo podem ser corrompidos quando o analisador JSON os converte ao tipo Number. Usando String em vez disso é uma possível alternativa para se evitar um resultado indesejado.

+ +

 Exemplo: Usando Number para converter um objeto Date

+ +

O exemplo a seguir converte o objeto Date para um valor numérico usando Number como uma função:

+ +
var d = new Date("December 17, 1995 03:24:00");
+print(Number(d));
+
+ +

Isto resulta em "819199440000".

+ +

Converte 'string' numérica em números

+ +
Number('123')     // 123
+Number('12.3')    // 12.3
+Number('')        // 0
+Number('0x11')    // 17
+Number('0b11')    // 3
+Number('0o11')    // 9
+Number('foo')     // NaN
+Number('100a')    // NaN
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentário
Primeiro edição ECMAScript. Implementado em JavaScript 1.1Padrãodefinição inicial.
{{SpecName('ES5.1', '#sec-15.7', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number-objects', 'Number')}}{{Spec2('ES6')}}Novos métodos e propriedades adicionadas (EPSILON, isFinite, isInteger, isNaN, parseFloat, parseInt)
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
ConfiguraçãoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ConfiguraçãoAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}{{ CompatVersionUnknown() }}
+
+ +

Veja também

+ + + +
 
diff --git a/files/pt-br/web/javascript/reference/global_objects/number/isfinite/index.html b/files/pt-br/web/javascript/reference/global_objects/number/isfinite/index.html new file mode 100644 index 0000000000..d4a86d3531 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/isfinite/index.html @@ -0,0 +1,86 @@ +--- +title: Number.isFinite() +slug: Web/JavaScript/Reference/Global_Objects/Number/isFinite +tags: + - JavaScript + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite +--- +
{{JSRef}}
+ +

O método Number.isFinite()  determina se o valor passado é um número finito.

+ +

Sintaxe

+ +
Number.isFinite(valor)
+ +

Parâmetros

+ +
+
valor
+
O valor a ser testado.
+
+ +

Retorno

+ +

Um {{jsxref("Boolean")}} indicando se o valor passado é ou não um número finito.

+ +

Descrição

+ +

Em comparação com a função global {{jsxref("isFinite", "isFinite()")}}, esse método não força a conversão do parâmetro para número. Isso significa que só valores do tipo número, que são também finitos, retornam true.

+ +

Exemplos

+ +
Number.isFinite(Infinity);  // false
+Number.isFinite(NaN);       // false
+Number.isFinite(-Infinity); // false
+
+Number.isFinite(0);         // true
+Number.isFinite(2e64);      // true
+
+Number.isFinite('0');       // false, teria sido true com a função
+                            // global isFinite('0')
+Number.isFinite(null);      // false, teria sido true com a função
+                            // global isFinite(null)
+
+ +

Polyfill

+ +
Number.isFinite = Number.isFinite || function(value) {
+    return typeof value === 'number' && isFinite(value);
+}
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Number.isFinite")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/isinteger/index.html b/files/pt-br/web/javascript/reference/global_objects/number/isinteger/index.html new file mode 100644 index 0000000000..fce6b5f19c --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/isinteger/index.html @@ -0,0 +1,136 @@ +--- +title: Number.isInteger() +slug: Web/JavaScript/Reference/Global_Objects/Number/isInteger +tags: + - Numérico + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isInteger +--- +
{{JSRef}}
+ +

O método Number.isInteger() determina se o valor passado é um inteiro.

+ +

Sintaxe

+ +
Number.isInteger(value)
+ +

Parâmetros

+ +
+
value
+
O valor a testar se é um inteiro.
+
+ +

Valor retornado

+ +

Um {{jsxref("Boolean")}} indicando se o valor é inteiro ou não.

+ +

Descrição

+ +

Se o alvo for um inteiro, returna true, senão returna false. Se o valor é {{jsxref("NaN")}} ou infinito, returna false.

+ +

Exemplos

+ +
Number.isInteger(0);         // true
+Number.isInteger(1);         // true
+Number.isInteger(-100000);   // true
+
+Number.isInteger(0.1);       // false
+Number.isInteger(Math.PI);   // false
+
+Number.isInteger(Infinity);  // false
+Number.isInteger(-Infinity); // false
+Number.isInteger("10");      // false
+Number.isInteger(true);      // false
+Number.isInteger(false);     // false
+Number.isInteger([1]);       // false
+
+ +

Polyfill

+ +
Number.isInteger = Number.isInteger || function(value) {
+  return typeof value === "number" &&
+    isFinite(value) &&
+    Math.floor(value) === value;
+};
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES6', '#sec-number.isinteger', 'Number.isInteger')}}{{Spec2('ES6')}}Definição inicial.
{{SpecName('ESDraft', '#sec-number.isinteger', 'Number.isInteger')}}{{Spec2('ESDraft')}}
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("16")}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome para AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Ver tabém

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/isnan/index.html b/files/pt-br/web/javascript/reference/global_objects/number/isnan/index.html new file mode 100644 index 0000000000..9652d6628c --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/isnan/index.html @@ -0,0 +1,131 @@ +--- +title: Number.isNaN() +slug: Web/JavaScript/Reference/Global_Objects/Number/isNaN +tags: + - Experimental + - Expérimental(2) + - JavaScript + - Method + - Number +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isNaN +--- +
{{JSRef("Global_Objects", "Number")}}
+ +

Resumo

+ +

O método Number.isNaN() determina se o valor passado é {{jsxref("Global_Objects/NaN", "NaN")}}. Versão mais robusta do original global {{jsxref("Global_Objects/isNaN", "isNaN")}}.

+ +

Sintaxe

+ +
Number.isNaN(testValue)
+ +

Parâmetros

+ +
+
testValue
+
O valor a ser testado por {{jsxref("Global_Objects/NaN", "NaN")}}.
+
+ +

Descrição

+ +

Devido a ambos os operadores de igualdade, == and ===, avaliar a false quando está verificando se {{jsxref("Global_Objects/NaN", "NaN")}} é NaN, a função Number.isNaN se torna necessária. Esta situação é diferente de todas as outras comparações de valor possível em JavaScript.

+ +

Em comparação a função global {{jsxref("Global_Objects/isNaN", "isNaN")}}, Number.isNaN não sofre do problema de forçar a conversão do parâmetro para um número. Isso significa que ele é seguro para passar valores que, normalmente, se convertem em NaN, mas na verdade não são o mesmo valor que NaN. Isto também significa que apenas os valores do número do tipo, que são também NaN, retorna true.

+ +

Exemplos

+ +
Number.isNaN(NaN); // true
+Number.isNaN(Number.NaN); // true
+Number.isNaN(0 / 0) // true
+
+// everything else: false
+Number.isNaN(undefined);
+Number.isNaN({});
+
+Number.isNaN(true);
+Number.isNaN(null);
+Number.isNaN(37);
+
+Number.isNaN("37");
+Number.isNaN("37.37");
+Number.isNaN("");
+Number.isNaN(" ");
+Number.isNaN("NaN");
+Number.isNaN("blabla"); // e.g. este teria sido true com isNaN
+ +

Especificações

+ + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
+

{{SpecName('ES6', '#sec-number.isnan', 'Number.isnan')}}

+
{{Spec2('ES6')}}Definição inicial.
+ +

Compatibilidade de navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico25.0{{CompatGeckoDesktop("15")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatNo}}{{ CompatUnknown() }}{{CompatGeckoMobile("15")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/issafeinteger/index.html b/files/pt-br/web/javascript/reference/global_objects/number/issafeinteger/index.html new file mode 100644 index 0000000000..b6b9d823bc --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/issafeinteger/index.html @@ -0,0 +1,104 @@ +--- +title: Number.isSafeInteger() +slug: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger +tags: + - JavaScript + - Número + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger +--- +
{{JSRef}}
+ +

O método Number.isSafeInteger() determina se o valor fornecido é seja um número seguro.

+ +
{{EmbedInteractiveExample("pages/js/number-issafeinteger.html")}}
+ + + +

Um inteiro seguro é um inteiro que:

+ + + +

Exemplo, 253 - 1 é um inteiro seguro: pode ser exatamente representado, e nenhum outro numero arredondado existe para ele na represetanção IEEE-754. Em contexto, 253 não é um inteiro seguro: pode ser representado em IEEE-754, mas um inteiro 253 + 1 não pode ser diretamente representado em IEEE-754 mas instanciado do arrendamento de 253 sob arrendamento para o mais próximo e do arrendamento de zero a zero. Os inteiros seguros consistem em todos os inteiros de -(253 - 1) inclusive para 253 - 1 (sendo ± 9007199254740991 ou ± 9,007,199,254,740,991).  

+ +

A manipulação de valores entre ~9 quadrilhões com precisão total requer o uso de arbitrary precision arithmetic library (biblioteca aritmética de precisão arbitrária).  Veja What Every Programmer Needs to Know about Floating Point Arithmetic (o que todo programador precisa saber sobre aritmética de ponto flutuante) para mais informações sobre represetanções de número de ponto flutuante.

+ +

Para números inteiros maiores, considere o uso do tipo {{jsxref("BigInt")}}.

+ +

Sintaxe

+ +
Number.isSafeInteger(valorTest)
+
+ +

Parâmetros

+ +
+
valorTest
+
O valor a ser testado pode ser um número inteiro seguro.
+
+
+ +

Retorno

+ +

Um {{jsxref("Boolean")}} indica se o valor fornecido é um número seguro ou não.

+ +

Exemplos

+ +
Number.isSafeInteger(3);                    // true
+Number.isSafeInteger(Math.pow(2, 53));      // false
+Number.isSafeInteger(Math.pow(2, 53) - 1);  // true
+Number.isSafeInteger(NaN);                  // false
+Number.isSafeInteger(Infinity);             // false
+Number.isSafeInteger('3');                  // false
+Number.isSafeInteger(3.1);                  // false
+Number.isSafeInteger(3.0);                  // true
+
+ +

Polyfill (caso não exista suporte)

+ +
Number.isSafeInteger = Number.isSafeInteger || function (value) {
+   return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
+};
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComéntario
{{SpecName('ES2015', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}{{Spec2('ES2015')}}Definição inicial
{{SpecName('ESDraft', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}{{Spec2('ESDraft')}}
+ +

Compatibilidade

+ + + +

{{Compat("javascript.builtins.Number.isSafeInteger")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/max_safe_integer/index.html b/files/pt-br/web/javascript/reference/global_objects/number/max_safe_integer/index.html new file mode 100644 index 0000000000..bae4c758f3 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/max_safe_integer/index.html @@ -0,0 +1,83 @@ +--- +title: Number.MAX_SAFE_INTEGER +slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER +tags: + - ECMAScript 2015 + - JavaScript + - Number + - Número + - Property + - Propriedade +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER +--- +
{{JSRef}}
+ +

A constante Number.MAX_SAFE_INTEGER representa o maior inteiro seguro no JavaScript (253 - 1).

+ +

Para inteiros maiores, considere usar {{jsxref("BigInt")}}.

+ +
{{EmbedInteractiveExample("pages/js/number-maxsafeinteger.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrição

+ +

A constante MAX_SAFE_INTEGER tem o valor de 9007199254740991 (9,007,199,254,740,991 ou ~9 quadrilhões). A razão por trás deste número é que o JavaScript usa o formato de número de ponto-flutuante de precisão-dupla como especificado na IEEE 754 e pode seguramente representar número entre -(253 - 1) e 253 - 1.

+ +

Seguro neste contexto se refere a habilidade de representar inteiros exatamente e corretamente compará-los. Por exemplo, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 será avaliado para verdadeiro, que é matematicamente incorreto. Veja {{jsxref("Number.isSafeInteger()")}} para mais informação.

+ +

Este campo não existe em navegadores antigos. Usando ele sem checar sua existência, como Math.max(Number.MAX_SAFE_INTEGER, 2), irá gerar resultados indesejados como NaN.

+ +

Por MAX_SAFE_INTEGER ser uma propriedade estática de {{jsxref("Number")}}, você sempre deve usar como Number.MAX_SAFE_INTEGER, ao invés de uma propriedade do objeto {{jsxref("Number")}} que você criou.

+ +

Polyfill

+ +
if (!Number.MAX_SAFE_INTEGER) {
+    Number.MAX_SAFE_INTEGER = 9007199254740991; // Math.pow(2, 53) - 1;
+}
+
+ +

Exemplos

+ +

Retorno do valor de MAX_SAFE_INTEGER

+ +
Number.MAX_SAFE_INTEGER; // 9007199254740991
+
+ +

Números maiores que o inteiro seguro

+ +

Isso retorna 2 por quê em pontos flutuantes, o valor é na verdade o final decimal "1" exceto em casos subnormais de precisão como zero.

+ +
Number.MAX_SAFE_INTEGER * Number.EPSILON; // 2
+
+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-number.max_safe_integer', 'Number.MAX_SAFE_INTEGER')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.builtins.Number.MAX_SAFE_INTEGER")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/max_value/index.html b/files/pt-br/web/javascript/reference/global_objects/number/max_value/index.html new file mode 100644 index 0000000000..2a308f13ed --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/max_value/index.html @@ -0,0 +1,65 @@ +--- +title: Number.MAX_VALUE +slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE +tags: + - JavaScript + - Number + - Property + - Propriedade + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE +--- +
{{JSRef}}
+ +

A propriedade Number.MAX_VALUE representa o maior valor numérico representável em JavaScript.

+ +
{{EmbedInteractiveExample("pages/js/number-maxvalue.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrição

+ +

A propriedade MAX_VALUE tem o valor de aproximadamente 1.79E+308, ou 21024. Valores maiores que MAX_VALUE são representados como {{jsxref("Infinity")}}.

+ +

Por MAX_VALUE ser uma propriedade estática de {{jsxref("Number")}}, você sempre deve usar como Number.MAX_VALUE, ao invés de uma propriedade do objeto {{jsxref("Number")}} que você criou. 

+ +

Exemplos

+ +

Usando MAX_VALUE

+ +

O código a seguir multiplica dois valores numéricos. Se o resultado é menor ou igual a MAX_VALUE, a função func1 é chamada; caso contrário, a função func2 é chamada.

+ +
if (num1 * num2 <= Number.MAX_VALUE) {
+  func1();
+} else {
+  func2();
+}
+
+ +

Especificações

+ + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-number.max_value', 'Number.MAX_VALUE')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.builtins.Number.MAX_VALUE")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/min_safe_integer/index.html b/files/pt-br/web/javascript/reference/global_objects/number/min_safe_integer/index.html new file mode 100644 index 0000000000..ab952dcadb --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/min_safe_integer/index.html @@ -0,0 +1,66 @@ +--- +title: Number.MIN_SAFE_INTEGER +slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER +tags: + - ECMAScript 2015 + - JavaScript + - Number + - Número + - Property + - Propriedade +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER +--- +
{{JSRef}}
+ +

A constante Number.MIN_SAFE_INTEGER representa o menor inteiro seguro no JavaScript (-(253 - 1)).

+ +

Para representar inteiros menores do que isso, considere usar {{jsxref("BigInt")}}.

+ +
{{EmbedInteractiveExample("pages/js/number-min-safe-integer.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrição

+ +

A constante MIN_SAFE_INTEGER tem o valor de -9007199254740991 (-9,007,199,254,740,991 ou -9 quadrilhões). A razão por trás deste número é que o JavaScript usa o formato de número de ponto-flutuante de precisão-dupla como especificado na IEEE 754 e pode seguramente representar número entre -(253 - 1) e 253 - 1.  Veja {{jsxref("Number.isSafeInteger()")}} para mais informações.

+ +

Por MIN_SAFE_INTEGER ser uma propriedade estática de {{jsxref("Number")}}, você sempre deve usar como Number.MIN_SAFE_INTEGER, ao invés de uma propriedade do objeto {{jsxref("Number")}} que você criou.

+ +

Exemplos

+ +

Usando MIN_SAFE_INTEGER

+ +
Number.MIN_SAFE_INTEGER // -9007199254740991
+-(Math.pow(2, 53) - 1)  // -9007199254740991
+
+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-number.min_safe_integer', 'Number.MIN_SAFE_INTEGER')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.builtins.Number.MIN_SAFE_INTEGER")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/min_value/index.html b/files/pt-br/web/javascript/reference/global_objects/number/min_value/index.html new file mode 100644 index 0000000000..6c6738f96f --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/min_value/index.html @@ -0,0 +1,69 @@ +--- +title: Number.MIN_VALUE +slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE +tags: + - JavaScript + - Number + - Número + - Property + - Propriedade + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE +--- +
{{JSRef}}
+ +

A propriedade Number.MIN_VALUE representa o menor valor positivo numérico representável em JavaScript.

+ +
{{EmbedInteractiveExample("pages/js/number-min-value.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrição

+ +

A propriedade MIN_VALUE é o número mais próximo de 0, não o número mais negativo, que o JavaScript pode representar.

+ +

MIN_VALUE tem o valor de aproximadamente 5e-324. Valores menores que MIN_VALUE ("valores de underflow") são convertidos para 0.

+ +

Por MIN_VALUE ser uma propriedade estática de {{jsxref("Number")}}, você sempre deve usar como Number.MIN_VALUE, ao invés de uma propriedade do objeto {{jsxref("Number")}} que você criou.

+ +

Exemplos

+ +

Usando MIN_VALUE

+ +

O seguinte código divide dois valores numéricos. Se o resultado é maior ou igual a MIN_VALUE, a função func1 é chamada; caso contrário, a função func2 é chamada.

+ +
if (num1 / num2 >= Number.MIN_VALUE) {
+  func1();
+} else {
+  func2();
+}
+
+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-number.min_value', 'Number.MIN_VALUE')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.builtins.Number.MIN_VALUE")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/nan/index.html b/files/pt-br/web/javascript/reference/global_objects/number/nan/index.html new file mode 100644 index 0000000000..d2c49dee98 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/nan/index.html @@ -0,0 +1,105 @@ +--- +title: Number.NaN +slug: Web/JavaScript/Reference/Global_Objects/Number/NaN +translation_of: Web/JavaScript/Reference/Global_Objects/Number/NaN +--- +
{{JSRef}}
+ +

A propriedade Number.NaN representa Not-A-Number (Não-Número). Equivalente a {{jsxref("NaN")}}.

+ +

Você não precisa criar um objeto {{jsxref("Number")}} para acessar esta propriedade estática (use Number.NaN).

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusDetalhes
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição Inicial. Implementado no JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.4', 'Number.NaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.nan', 'Number.NaN')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.nan', 'Number.NaN')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de Navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte Básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

 

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/negative_infinity/index.html b/files/pt-br/web/javascript/reference/global_objects/number/negative_infinity/index.html new file mode 100644 index 0000000000..ca9531f930 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/negative_infinity/index.html @@ -0,0 +1,84 @@ +--- +title: Number.NEGATIVE_INFINITY +slug: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY +tags: + - JavaScript + - Number + - Número + - Property + - Propriedade + - Referencia +translation_of: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY +--- +
{{JSRef}}
+ +

A propriedade Number.NEGATIVE_INFINITY representa o valor Infinito negativo.

+ +
{{EmbedInteractiveExample("pages/js/number-negative-infinity.html")}}
+ + + +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrição

+ +

O valor de Number.NEGATIVE_INFINITY é o mesmo que o valor negativo da propriedade do objeto global {{jsxref("Infinity")}}.

+ +

O valor se comporta um pouco diferente do que o infinito matemático:

+ + + +

Você pode usar a propriedade Number.NEGATIVE_INFINITY para indicar uma condição de erro que retorna um número finito em caso de sucesso. Nota que, usar {{jsxref("isFinite")}} seria mais apropriado neste caso.

+ +

Por NEGATIVE_INFINITY ser uma propriedade estática de {{jsxref("Number")}}, você sempre a usa como Number.NEGATIVE_INFINITY, ao invés de ser uma propriedade do objeto {{jsxref("Number")}} que você criou.

+ +

Exemplos

+ +

Usando NEGATIVE_INFINITY

+ +

No seguinte exemplo, a variável smallNumber é atribuída um valor que é menor que o valor mínimo. Quando o {{jsxref("Statements/if...else", "if")}} executa, smallNumber tem o valor -Infinity, então é colocado em smallNumber um valor mais manejável antes de continuar.

+ +
var smallNumber = (-Number.MAX_VALUE) * 2;
+
+if (smallNumber === Number.NEGATIVE_INFINITY) {
+  smallNumber = returnFinite();
+}
+
+ +

Especificações

+ + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.builtins.Number.NEGATIVE_INFINITY")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/parsefloat/index.html b/files/pt-br/web/javascript/reference/global_objects/number/parsefloat/index.html new file mode 100644 index 0000000000..85994f5ca6 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/parsefloat/index.html @@ -0,0 +1,116 @@ +--- +title: Number.parseFloat() +slug: Web/JavaScript/Reference/Global_Objects/Number/parseFloat +translation_of: Web/JavaScript/Reference/Global_Objects/Number/parseFloat +--- +
{{JSRef("Global_Objects", "Number")}}
+ +

Resumo

+ +

O método Number.parseFloat() converte a string recebida como argumento e a retorna como um número de ponto flutuante. Este método se comporta de maneira idêntica a da função global {{jsxref("Global_Objects/parseFloat", "parseFloat")}} e é parte da especificação ECMAScript 6 (seu propósito é a modularização dos objetos globais).

+ +

Sintaxe

+ +
Number.parseFloat(string)
+ +

Parâmetros

+ +
+
string
+
Uma string que represente o valor que se deseja converter.
+  
+
+ +

Retorno

+ +
+
string
+
Um número de ponto flutuante a partir da string dada. Se a string não puder ser convertida em para um número, {{jsxref("Global_Objects/NaN","NaN")}} é retornado.
+
+ +

Descrição

+ +

Este método tem a mesma funcionalidade do método global:  {{jsxref("Global_Objects/parseFloat", "parseFloat()")}}

+ +
Number.parseFloat === parseFloat; // true
+
+ +

Por favor veja {{jsxref("parseFloat", "parseFloat()")}} para mais detalhes e exemplos.

+ +

Especificação

+ + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentários
+

{{SpecName('ES6', '#sec-number.parsefloat', 'Number.parseFloat')}}

+
{{Spec2('ES6')}}Definição inicial.
+ +

Compatibilidade dos Navegadores

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
RecursoChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatNo}}{{CompatGeckoDesktop("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
RecursoAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/parseint/index.html b/files/pt-br/web/javascript/reference/global_objects/number/parseint/index.html new file mode 100644 index 0000000000..88c3c6735b --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/parseint/index.html @@ -0,0 +1,85 @@ +--- +title: Number.parseInt() +slug: Web/JavaScript/Reference/Global_Objects/Number/parseInt +tags: + - ECMAScript 2015 + - JavaScript + - Method + - Number + - Número + - metodo +translation_of: Web/JavaScript/Reference/Global_Objects/Number/parseInt +--- +
{{JSRef}}
+ +

O método Number.parseInt() converte um argumento de string e retorna um inteiro da raiz ou base específica.

+ +
{{EmbedInteractiveExample("pages/js/number-parseint.html", "taller")}}
+ + + +

Sintaxe

+ +
Number.parseInt(string,[ radix])
+ +

Parâmetros

+ +
+
+
string
+
O valor a ser convertido. Se este argumento não for uma string, então ele é convertido a um usando a operação abstrata ToString. O espaço em branco inicial neste argumento é ignorado.
+
radix {{optional_inline}}
+
Um inteiro entre 2 e 36 que representa a raiz (a base no sistema numérico matemático) de uma string. Tome cuidado—o padrão não é 10!
+
+
+ +

Valor de retorno

+ +

Um inteiro convertido de uma dada string.

+ +

Se a radix é menor que 2 ou maior que 36, e o primeiro caracter que não é um espaço em branco não puder ser convertido para um número, {{jsxref("NaN")}} é retornado.

+ +

Polyfill

+ +
if (Number.parseInt === undefined) {
+    Number.parseInt = window.parseInt
+}
+
+ +

Exemplos

+ +

Number.parseInt vs parseInt

+ +

Este método tem a mesma funcionalidade que o método global {{jsxref("parseInt", "parseInt()")}}:

+ +
Number.parseInt === parseInt // true
+ +

e é parte do ECMAScript 2015 (sua proposta é a modularização dos globais). Por favor veja {{jsxref("parseInt", "parseInt()")}} para mais detalhes e exemplos.

+ +

Especificações

+ + + + + + + + + + + + +
Especificação
{{SpecName('ESDraft', '#sec-number.parseint', 'Number.parseInt')}}
+ +

Compatibilidade de navegador

+ + + +

{{Compat("javascript.builtins.Number.parseInt")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/positive_infinity/index.html b/files/pt-br/web/javascript/reference/global_objects/number/positive_infinity/index.html new file mode 100644 index 0000000000..b6ac31f1ec --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/positive_infinity/index.html @@ -0,0 +1,92 @@ +--- +title: Number.POSITIVE_INFINITY +slug: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY +translation_of: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY +--- +
{{JSRef}}
+ +

A propriedade Number.POSITIVE_INFINITY representa o valor positivo infinito.

+ +

Você não precisa criar um objeto {{jsxref("Number")}} para utilizar a propriedade estática (use Number.POSITIVE_INFINITY).

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrição

+ +

O valor de Number.POSITIVE_INFINITY é o mesmo valor da propriedade {{jsxref("Infinity")}} do objeto global.

+ +

Esse valor se comporta ligeiramente diferente do infinito matemático:

+ + + +

Você pode usar a propriedade Number.POSITIVE_INFINITY para indicar uma condição de erro que retorna um número finito no caso de sucesso. Sobretudo, {{jsxref("isFinite")}} seria mais apropriado nesse caso.

+ +

Exemplos

+ +

Usando POSITIVE_INFINITY

+ +

No exemplo a seguir, a variável bigNumber recebe um valor maior que o valor máximo. Quando as declarações {{jsxref("Statements/if...else", "if")}} executam, bigNumber tem o valor Infinity, então bigNumber recebe um valor mais gerenciável antes de continuar.

+ +
var bigNumber = Number.MAX_VALUE * 2;
+
+if (bigNumber == Number.POSITIVE_INFINITY) {
+  bigNumber = returnFinite();
+}
+
+ +

Especificação

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.6', 'Number.POSITIVE_INFINITY')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.positive_infinity', 'Number.POSITIVE_INFINITY')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.positive_infinity', 'Number.POSITIVE_INFINITY')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade dos browsers

+ + + +

{{Compat("javascript.builtins.Number.POSITIVE_INFINITY")}}

+ +

Ver também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/prototype/index.html b/files/pt-br/web/javascript/reference/global_objects/number/prototype/index.html new file mode 100644 index 0000000000..01b988c542 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/prototype/index.html @@ -0,0 +1,139 @@ +--- +title: Number.prototype +slug: Web/JavaScript/Reference/Global_Objects/Number/prototype +tags: + - JavaScript + - Número + - Propriedade + - Prototipo +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +
{{JSRef}}
+ +

A propriedade Number.prototype representa o protótipo para o construtor {{jsxref("Number")}}.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Descrição

+ +

Todas instâncias {{jsxref("Number")}} herdam de Number.prototype. O objeto 'prototype' do construtor {{jsxref("Number")}} pode ser modificado para afetar todas instâncias {{jsxref( "Number")}}.

+ +

Propriedades

+ +
+
Number.prototype.constructor
+
Retorna a função que criou esta instância do objeto. Por padrão, este é o objeto {{jsxref("Number")}}.
+
+ +

Métodos

+ +
+
{{jsxref("Number.prototype.toExponential()")}}
+
Retorna uma 'string' representando o número em notação exponencial.
+
{{jsxref("Number.prototype.toFixed()")}}
+
Retorna uma 'string' representando o número em notação em ponto fixo.
+
{{jsxref("Number.prototype.toLocaleString()")}}
+
Retorna uma 'string'  com uma representação sensível ao idioma deste número.  Substitui o método {{jsxref("Object.prototype.toLocaleString()")}}.
+
{{jsxref("Number.prototype.toPrecision()")}}
+
Retorna uma 'string' representando o número para uma precisão específica em notação ponto fixo ou exponencial.
+
{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}
+
Retorna uma objeto literal representando um objeto específicado {{jsxref("Number")}}; você pode usar este valor para criar um novo objeto. Substitui o método {{jsxref("Object.prototype.toSource()")}}.
+
{{jsxref("Number.prototype.toString()")}}
+
Retorna uma 'string' representando o objeto especificado na raiz especificada (base). Substitui o método {{jsxref("Object.prototype.toString()")}}.
+
{{jsxref("Number.prototype.valueOf()")}}
+
Retorna o valor primitivo do objeto especificado. Substitui o método {{jsxref("Object.prototype.valueOf()")}}.
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoSituaçãoComentários
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementado em JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
ConfiguraçãoChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
ConfiguraçãoAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suporte básico{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/toexponential/index.html b/files/pt-br/web/javascript/reference/global_objects/number/toexponential/index.html new file mode 100644 index 0000000000..743a4b32b0 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/toexponential/index.html @@ -0,0 +1,149 @@ +--- +title: Number.prototype.toExponential() +slug: Web/JavaScript/Reference/Global_Objects/Number/toExponential +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toExponential +--- +
{{JSRef}}
+ +

O método toExponential() retorna uma string  representando o objeto {{jsxref("Global_Objects/Number", "Number")}} por meio de notação exponencial.

+ +

Syntax

+ +
numObj.toExponential([fractionDigits])
+ +

Parameters

+ +
+
fractionDigits
+
Optional. An integer specifying the number of digits after the decimal point. Defaults to as many digits as necessary to specify the number.
+
+ +

Return value

+ +

A string representing the given {{jsxref("Number")}} object in exponential notation with one digit before the decimal point, rounded to fractionDigits digits after the decimal point.

+ +

Exceptions

+ +
+
{{jsxref("RangeError")}}
+
If fractionDigits is too small or too large. Values between 0 and 20, inclusive, will not cause a {{jsxref("RangeError")}}. Implementations are allowed to support larger and smaller values as well.
+
{{jsxref("TypeError")}}
+
If this method is invoked on an object that is not a {{jsxref("Number")}}.
+
+ +

Description

+ +

If the fractionDigits argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely.

+ +

If you use the toExponential() method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point.

+ +

If a number has more digits than requested by the fractionDigits parameter, the number is rounded to the nearest number represented by fractionDigits digits. See the discussion of rounding in the description of the {{jsxref("Number.prototype.toFixed", "toFixed()")}} method, which also applies to toExponential().

+ +

Examples

+ +

Using toExponential

+ +
var numObj = 77.1234;
+
+console.log(numObj.toExponential());  // logs 7.71234e+1
+console.log(numObj.toExponential(4)); // logs 7.7123e+1
+console.log(numObj.toExponential(2)); // logs 7.71e+1
+console.log(77.1234.toExponential()); // logs 7.71234e+1
+console.log(77 .toExponential());     // logs 7.7e+1
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.7.4.6', 'Number.prototype.toExponential')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.toexponential', 'Number.prototype.toExponential')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.prototype.toexponential', 'Number.prototype.toExponential')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

See also

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/tofixed/index.html b/files/pt-br/web/javascript/reference/global_objects/number/tofixed/index.html new file mode 100644 index 0000000000..1b64e75c82 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/tofixed/index.html @@ -0,0 +1,99 @@ +--- +title: Number.prototype.toFixed() +slug: Web/JavaScript/Reference/Global_Objects/Number/toFixed +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toFixed +--- +
{{JSRef}}
+ +

O método toFixed() formata um número utilizando notação de ponto fixo.

+ +

Sintaxe

+ +
numObj.toFixed([dígitos])
+ +

Parâmetros

+ +
+
dígitos
+
Opcional. O número de dígitos que aparecem depois do ponto decimal; este pode ser um valor entre 0 e 20, inclusive, e algumas implementacões podem suportar uma variação de números maiores. Se este argumento for omitido, será tratado como 0. 
+
+ +

Retorno

+ +

Uma string representando o número usando notação em ponto fixo.

+ +

Throws

+ +
+
{{jsxref("RangeError")}}
+
Se dígitos for muito pequeno ou muito grande. Valores entre 0 e 20, inclusive, não irão causar o {{jsxref("RangeError")}}. É permitido às implementações suportar valores maiores e menores.
+
{{jsxref("TypeError")}}
+
Se este método for chamado em um objeto que não é {{jsxref( "Number")}}.
+
+ + +

Descrição

+

Uma string representando numObj que não usa notação exponencial e tem exatamente dígitos dígitos depois da casa decimal. O número será arredondado se necessário, e será adicionado zeros a parte após a virgula para que este tenha o tamanho que foi especificado. Se o numObj for maior que 1e+21, entao será invocado o método {{jsxref("Number.prototype.toString()")}} e será retornado uma string em notação exponencial.

+ +

Exemplos

+ +

Utilizando toFixed

+ +
var numObj = 12345.6789;
+
+numObj.toFixed();       // Retorna '12346': note o arredondamento, não possui nenhuma parte fracionária
+numObj.toFixed(1);      // Retorna '12345.7': note o arredondamento
+numObj.toFixed(6);      // Retorna '12345.678900': note que adicionou zeros
+(1.23e+20).toFixed(2);  // Retorna '123000000000000000000.00'
+(1.23e-10).toFixed(2);  // Retorna '0.00'
+2.34.toFixed(1);        // Retorna '2.3'
+2.35.toFixed(1);        // Retorna '2.4'. Note que arredonda para cima neste caso.
+-2.34.toFixed(1);       // Retorna -2.3 (devido à precedência do operador, literais de números negativos não retornam uma string...)
+(-2.34).toFixed(1);     // Retorna '-2.3' (...a menos que se utilize parênteses)
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Definição incial. Implementada no JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.7.4.5', 'Number.prototype.toFixed')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}}{{Spec2('ESDraft')}} 
+ +

Compatibilidade dos navegadores

+ +
{{CompatibilityTable}}
+ +{{Compat("javascript.builtins.Number.toFixed")}} + +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/tolocalestring/index.html b/files/pt-br/web/javascript/reference/global_objects/number/tolocalestring/index.html new file mode 100644 index 0000000000..d4ced2ffff --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/tolocalestring/index.html @@ -0,0 +1,176 @@ +--- +title: Number.prototype.toLocaleString() +slug: Web/JavaScript/Reference/Global_Objects/Number/toLocaleString +tags: + - Internacionalização + - JavaScript + - Método(2) + - Number + - Número + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toLocaleString +--- +
{{JSRef}}
+ +

O método toLocaleString() retorna uma string com uma representação sensível a linguagem deste número.

+ +

Os novos argumentos locales e options permitem às aplicações especificar a linguagem cujas convenções de formatações serão utilizadas e personalizar o comportamento da função. Nas implementações anteriores, que ignorava os argumentos locales e options arguments, a localização utilizada e a forma de retornar a string erão totalmente dependente da implementação.

+ +

Sintaxe

+ +
numObj.toLocaleString([locales [, options]])
+ +

Parâmetros

+ +

Dê uma olhada na seção Compatibilidade do Navegador para verificar quais navegadores suportam os argumentos locales e options, e o Exemplo: Verificando o suporte dos argumentos locales e options para detecção desta característica.

+ +
+

Nota: ECMAScript Internationalization API, implementada com o Firefox 29, incluiu o argumento locales ao método Number.toLocaleString(). Se o argumento for {{jsxref("undefined")}}, este método retorna os dígitos de localização especificados pelo SO, enquanto que as versões anteriores doFirefox retornavam os dígitos Árabe Ocidental. Esta mudança foi relatada como uma regressão que afeta a retrocompatibilidade que será corrigida em breve. ({{bug(999003)}})

+
+ +
{{page('pt-BR/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat', 'Parâmetros')}}
+ +

Exemplos

+ +

Usando toLocaleString

+ +

No uso básico sem a especificação de uma localização, o método retornará uma string formatada com a localização e as opções padrão.

+ +
var numero = 3500;
+
+console.log(numero.toLocaleString()); // Mostra "3,500" se a localização for U.S. English
+
+ +

Verificando o suporte dos argumentos locales e options

+ +

Os argumentos locales e options não são suportados por todos os navegadores ainda. Para verificar pelo suporte das implementações do ES5.1 e posteriores, a requisição de tags de linguagem ilegais são rejeitadas com uma exceção {{jsxref("Global_Objects/RangeError", "RangeError")}} pode ser usada da seguinte forma:

+ +
function toLocaleStringSupportsLocales() {
+  var numero = 0;
+  try {
+     numero.toLocaleString('i');
+  } catch (e) {
+    return e.name === 'RangeError';
+  }
+  return false;
+}
+
+ +

Antes da ES5.1, implementações que não exigiam um tratamento de erro se toLocaleString fosse chamada com argumentos.

+ +

Uma verificação que funciona em todos os casos, incluindo aqueles que suportam ECMA-262 antes da edição 5.1, é testar pelas especificações de característicadas da ECMA-402 que exigem suporte de opções regionais para Number.prototype.toLocaleString diretamente:

+ +
function toLocaleStringSupportsOptions() {
+  return !!(typeof Intl == 'object' && Intl && typeof Intl.NumberFormat == 'function');
+}
+
+ +

Estes testes para um objeto Intl global, verifica se ele não é null e se uma propriedade NumberFormat é uma função.

+ +

Usando locales

+ +

Este exemplo mostra algumas variações de formatos de números localizados. A fim de obter o formato da linguagem utilizada na interface do usuário da sua aplicação, tenha certeza de especificar a língua (e possivelmente algumas línguas reservas) usando o argumento locales:

+ +
var numero = 123456.789;
+
+// O alemão usa vírgula como separador de decimal e ponto para milhares
+console.log(numero.toLocaleString('de-DE'));
+// → 123.456,789
+
+// O árabe usa dígitos Árabes Orientais em muitos países que falam árabe
+console.log(numero.toLocaleString('ar-EG'));
+// → ١٢٣٤٥٦٫٧٨٩
+
+// A Índia usa separadores de milhares/cem mil/dez milhões
+console.log(numero.toLocaleString('en-IN'));
+// → 1,23,456.789
+
+// A chave de extensão nu requer um sistema de numeração, ex. decimal chinês
+console.log(numero.toLocaleString('zh-Hans-CN-u-nu-hanidec'));
+// → 一二三,四五六.七八九
+
+// Quando informada uma língua sem suporte, como balinês,
+// inclua uma língua reseva, neste caso indonésio
+console.log(numero.toLocaleString(['ban', 'id']));
+// → 123.456,789
+
+ +

Usando options

+ +

Os resultados obtidos por toLocaleString pode ser personalizado usando o argumento options:

+ +
var numero = 123456.789;
+
+// informando um formato de moeda
+console.log(numero.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
+// → 123.456,79 €
+
+// o yen japonês não tem uma unidade menor
+console.log(numero.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
+// → ¥123,457
+
+// limitando a três dígitos significativos
+console.log(numero.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
+// → 1,23,000
+
+ +

Desempenho

+ +

Quando formatar uma grande quantidade de números, é melhor criar um objeto {{jsxref("NumberFormat")}} e usar a função fornecida pela propriedade {{jsxref("NumberFormat.format")}}.

+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Definição inicial. Implementado no JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.7.4.3', 'Number.prototype.toLocaleString')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.tolocalestring', 'Number.prototype.toLocaleString')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.prototype.tolocalestring', 'Number.prototype.toLocaleString')}}{{Spec2('ESDraft')}} 
{{SpecName('ES Int 1.0', '#sec-13.2.1', 'Number.prototype.toLocaleString')}}{{Spec2('ES Int 1.0')}} 
{{SpecName('ES Int 2.0', '#sec-13.2.1', 'Number.prototype.toLocaleString')}}{{Spec2('ES Int 2.0')}} 
{{SpecName('ES Int Draft', '#sec-Number.prototype.toLocaleString', 'Number.prototype.toLocaleString')}}{{Spec2('ES Int Draft')}} 
+ +

Compatibilidade do navegador

+ +

{{Compat("javascript.builtins.Number.toLocaleString")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/toprecision/index.html b/files/pt-br/web/javascript/reference/global_objects/number/toprecision/index.html new file mode 100644 index 0000000000..643a0b9a08 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/toprecision/index.html @@ -0,0 +1,104 @@ +--- +title: Number.prototype.toPrecision() +slug: Web/JavaScript/Reference/Global_Objects/Number/toPrecision +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toPrecision +--- +
{{JSRef}}
+ +
+ +

O método toPrecision() retorna uma string que representa o valor do objeto {{jsxref("Number")}} com uma precisão específica.

+ +
{{EmbedInteractiveExample("pages/js/number-toprecision.html")}}
+ +

Sintaxe

+ +
numObj.toPrecision([precisão])
+ +

Parâmetros

+ +
+
precisão
+
Opcional. Um inteiro especificando o número de algarismos significativos.
+
+ +

Retorno

+ +

Uma string representando um objeto {{jsxref("Number")}} em notação de ponto fixo ou exponencial arredondada segundo o parâmetro precisão. Veja a discussão sobre arredondamento feita na documentação do método {{jsxref("Number.prototype.toFixed()")}}, que também se aplica ao método toPrecision().

+ +

Se o parâmetro precisão for omitido, este método terá o mesmo comportamento de {{jsxref("Number.prototype.toString()")}}. Se o parâmetro precisão for um valor não inteiro, ele será arredondado para a sua representação mais próxima em inteiro.

+ +

Exceções

+ +
+
{{jsxref("Global_Objects/RangeError", "RangeError")}}
+
Se o valor de precisão não estiver compreendido entre 1 e 100 (inclusive), um  {{jsxref("RangeError")}} será lançado. É permitido às implementações suportar valores menores e maiores que esses, sendo um requisito do ECMA-262 que seja dado suporte a uma precisão de até 21 algarismos significativos.
+
+ +

Exemplos

+ +

Utilizando toPrecision

+ +
var numObj = 5.123456;
+
+console.log(numObj.toPrecision());    // logs '5.123456'
+console.log(numObj.toPrecision(5));   // logs '5.1235'
+console.log(numObj.toPrecision(2));   // logs '5.1'
+console.log(numObj.toPrecision(1));   // logs '5'
+
+numObj = 0.000123
+
+console.log(numObj.toPrecision());    // logs '0.000123'
+console.log(numObj.toPrecision(5));   // logs '0.00012300'
+console.log(numObj.toPrecision(2));   // logs '0.00012'
+console.log(numObj.toPrecision(1));   // logs '0.0001'
+
+// observe que a notação exponencial pode ser retornado em alguns casos
+console.log((1234.5).toPrecision(2)); // logs '1.2e+3'
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoEstadoComentário
{{SpecName('ES3')}}{{Spec2('ES3')}}Definição inicial. Implementada no JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.7.4.7', 'Number.prototype.toPrecision')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-number.prototype.toprecision', 'Number.prototype.toPrecision')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-number.prototype.toprecision', 'Number.prototype.toPrecision')}}{{Spec2('ESDraft')}}
+ +

Compatibilidade com navegadores

+ + + +

{{Compat("javascript.builtins.Number.toPrecision")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/tosource/index.html b/files/pt-br/web/javascript/reference/global_objects/number/tosource/index.html new file mode 100644 index 0000000000..8d10118b0a --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/tosource/index.html @@ -0,0 +1,48 @@ +--- +title: Number.prototype.toSource() +slug: Web/JavaScript/Reference/Global_Objects/Number/toSource +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toSource +--- +
{{JSRef}} {{non-standard_header}}
+ +

O método toSource() retorna uma string contendo o código fonte do objeto.

+ +

Syntax

+ +
numObj.toSource()
+Number.toSource()
+ +

Valor retornado

+ +

Uma string contendo o código fonte do objeto.

+ +

Descrição

+ +

O método toSource() retorna os seguintes valores:

+ +

Para o objeto built-in {{jsxref("Number")}}, o método toSource() retorna a seguinte string indicando que o código fonte do objeto não está disponível:

+ +
function Number() {
+    [native code]
+}
+
+ +

Para instâncias do objeto {{jsxref("Number")}}, toSource() retorna uma string contendo o código fonte.

+ +

Este método normalmente é invocado internamente pelo JavaScript e não explicitamente em um código web.

+ +

Especificações

+ +

Não é parte de nenhuma especificação padrão. Implementado no JavaScript 1.3.

+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Number.toSource")}}

+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/tostring/index.html b/files/pt-br/web/javascript/reference/global_objects/number/tostring/index.html new file mode 100644 index 0000000000..6ebd43e978 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/tostring/index.html @@ -0,0 +1,143 @@ +--- +title: Number.prototype.toString() +slug: Web/JavaScript/Reference/Global_Objects/Number/toString +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toString +--- +
{{JSRef("Global_Objects", "Number")}}
+ +

Resumo

+ +

O método toString() retorna uma string representando o objeto {{jsxref("Global_Objects/Number", "Number")}} especificado.

+ +

Sintaxe

+ +
numObj.toString([radix])
+ +

Parâmetros

+ +
+
radix
+
Opcional. Um inteiro entre 2 e 36 especificando a base utilizada para representar os valores numéricos.
+
+ +

Exceções

+ +
+
{{jsxref("Global_Objects/RangeError", "RangeError")}}
+
se toString() receber um valor de radix fora do intervalo entre 2 e 36, uma exceção {{jsxref("Global_Objects/RangeError", "RangeError")}} é lançada.
+
+ +

Descrição

+ +

O objeto {{jsxref("Global_Objects/Number", "Number")}} sobrescreve o método toString() do objeto {{jsxref("Global_Objects/Object", "Object")}}; ele não herda  de {{jsxref("Object.prototype.toString()")}}. Para objetos {{jsxref("Global_Objects/Number", "Number")}}, o método toString() retorna uma representação string do objeto na base especificada.

+ +

O método toString() analisa seu primeiro argumento e tenta retornar uma representação string na raiz (base) especificada. Para raizes maiores que 10, as letras do alfabeto indicam valores maiores que 9. Por exemplo, para números hexadecimais (base 16),  letras entre a e f são utilizadas.

+ +

Se o radix não for especificado, a raiz assumida como preferencial é a 10.

+ +

Se o numObj for negativo, o sinal é preservado. Isto acontece mesmo se a raiz for 2; a string retornada é a representação binária positiva de numObj precedida por um sinal - e não o complemento de dois do numObj.

+ +

Exemplos

+ +

Exemplo: Usando toString

+ +
var count = 10;
+
+console.log(count.toString());    // displays '10'
+console.log((17).toString());     // displays '17'
+
+var x = 6;
+
+console.log(x.toString(2));       // displays '110'
+console.log((254).toString(16));  // displays 'fe'
+
+console.log((-10).toString(2));   // displays '-1010'
+console.log((-0xff).toString(2)); // displays '-11111111'
+
+ +

Especificações

+ + + + + + + + + + + + + + + + + + + + + + + + +
EspecificaçãoStatusComentários
ECMAScript 1ª edição.StandardDefinição inicial. Implementado no JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4.2', 'Number.prototype.tostring')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.tostring', 'Number.prototype.tostring')}}{{Spec2('ES6')}} 
+ +

Compatibilidade de navegadores

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Veja também

+ + diff --git a/files/pt-br/web/javascript/reference/global_objects/number/valueof/index.html b/files/pt-br/web/javascript/reference/global_objects/number/valueof/index.html new file mode 100644 index 0000000000..7406994df7 --- /dev/null +++ b/files/pt-br/web/javascript/reference/global_objects/number/valueof/index.html @@ -0,0 +1,80 @@ +--- +title: Number.prototype.valueOf() +slug: Web/JavaScript/Reference/Global_Objects/Number/valueOf +translation_of: Web/JavaScript/Reference/Global_Objects/Number/valueOf +--- +
{{JSRef}}
+ +

O método valueOf() retorna o valor primitivo contido no objeto {{jsxref("Number")}}.

+ +
{{EmbedInteractiveExample("pages/js/number-valueof.html")}}
+ + + +

Sintaxe

+ +
numObj.valueOf()
+ +

Valor retornado

+ +

Um número representando o valor primitivo do objeto {{jsxref("Number")}}.

+ +

Descrição

+ +

Este método normalmente é invocado internamente pelo JavaScript e não explicitamente em um código web.

+ +

Exemplos

+ +

Utilizando valueOf

+ +
var numObj = new Number(10);
+console.log(typeof numObj); // object
+
+var num = numObj.valueOf();
+console.log(num);           // 10
+console.log(typeof num);    // number
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Definição inicial. Implementada no JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4.4', 'Number.prototype.valueOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.valueof', 'Number.prototype.valueOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.prototype.valueof', 'Number.prototype.valueOf')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Number.valueOf")}}

+ +

See also

+ + -- cgit v1.2.3-54-g00ecf