.
-So here we'll talk about regular numbers. Let's expand our knowledge of them.
+Aquí hablaremos de números regulares. Ampliemos lo que ya sabemos de ellos.
-## More ways to write a number
+## Más formas de escribir un número
-Imagine we need to write 1 billion. The obvious way is:
+Imagina que necesitamos escribir mil millones (En inglés "1 billion"). La forma obvia es:
```js
let billion = 1000000000;
```
-But in real life, we usually avoid writing a long string of zeroes as it's easy to mistype. Also, we are lazy. We will usually write something like `"1bn"` for a billion or `"7.3bn"` for 7 billion 300 million. The same is true for most large numbers.
+Pero en la vida real tratamos de evitar esribir una larga cadena de ceros porque es fácil tipear mal.
-In JavaScript, we shorten a number by appending the letter `"e"` to the number and specifying the zeroes count:
+En JavaScript, acortamos un número agregando la letra `"e"` y especificando la cantidad de ceros:
```js run
-let billion = 1e9; // 1 billion, literally: 1 and 9 zeroes
+let billion = 1e9; // 1 billion, literalmente: 1 y 9 ceros
alert( 7.3e9 ); // 7.3 billions (7,300,000,000)
```
-In other words, `"e"` multiplies the number by `1` with the given zeroes count.
+En otras palabras, `"e"` multiplica el número por el `1` seguido de la cantidad de ceros dada.
```js
1e3 = 1 * 1000
1.23e6 = 1.23 * 1000000
```
-Now let's write something very small. Say, 1 microsecond (one millionth of a second):
+Ahora escribamos algo muy pequeño. Digamos 1 microsegundo (un millonésimo de segundo):
```js
let ms = 0.000001;
```
-Just like before, using `"e"` can help. If we'd like to avoid writing the zeroes explicitly, we could say the same as:
+Como antes, el uso de `"e"` puede ayudar. Si queremos evitar la escritura de ceros explícitamente, podríamos expresar lo mismo así:
```js
-let ms = 1e-6; // six zeroes to the left from 1
+let ms = 1e-6; // seis ceros a la izquierda de 1
```
-If we count the zeroes in `0.000001`, there are 6 of them. So naturally it's `1e-6`.
+Si contamos los ceros en `0.000001`, hay 6 de ellos. Entonces naturalmente es `1e-6`.
-In other words, a negative number after `"e"` means a division by 1 with the given number of zeroes:
+En otras palabras, un número negativo detrás de `"e"` significa una división por el 1 seguido de la cantidad dada de ceros:
```js
-// -3 divides by 1 with 3 zeroes
+// -3 divide por 1 con 3 ceros
1e-3 = 1 / 1000 (=0.001)
-// -6 divides by 1 with 6 zeroes
+// -6 divide por 1 con 6 ceros
1.23e-6 = 1.23 / 1000000 (=0.00000123)
```
-### Hex, binary and octal numbers
+### Números hexadecimales, binarios y octales
-[Hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) numbers are widely used in JavaScript to represent colors, encode characters, and for many other things. So naturally, there exists a shorter way to write them: `0x` and then the number.
+Los números [Hexadecimales](https://es.wikipedia.org/wiki/Sistema_hexadecimal) son ampliamente usados en JavaScript para representar colores, codificar caracteres y muchas otras cosas. Es natural que exista una forma breve de escribirlos: `0x` y luego el número.
-For instance:
+Por ejemplo:
```js run
alert( 0xff ); // 255
-alert( 0xFF ); // 255 (the same, case doesn't matter)
+alert( 0xFF ); // 255 (lo mismo en mayúsculas o minúsculas )
```
-Binary and octal numeral systems are rarely used, but also supported using the `0b` and `0o` prefixes:
+Los sistemas binario y octal son raramente usados, pero también soportados mediante el uso de los prefijos `0b` y `0o`:
```js run
-let a = 0b11111111; // binary form of 255
-let b = 0o377; // octal form of 255
+let a = 0b11111111; // binario de 255
+let b = 0o377; // octal de 255
-alert( a == b ); // true, the same number 255 at both sides
+alert( a == b ); // true, el mismo número 255 en ambos lados
```
-There are only 3 numeral systems with such support. For other numeral systems, we should use the function `parseInt` (which we will see later in this chapter).
+Solo 3 sistemas numéricos tienen tal soporte. Para otros sistemas numéricos, debemos usar la función `parseInt` (que veremos luego en este capítulo).
## toString(base)
-The method `num.toString(base)` returns a string representation of `num` in the numeral system with the given `base`.
+El método `num.toString(base)` devuelve la representación `num` en una cadena, en el sistema numérico con la `base` especificada.
-For example:
+Ejemplo:
```js run
let num = 255;
@@ -92,45 +92,45 @@ alert( num.toString(16) ); // ff
alert( num.toString(2) ); // 11111111
```
-The `base` can vary from `2` to `36`. By default it's `10`.
+La `base` puede variar entre `2` y `36`. La predeterminada es `10`.
-Common use cases for this are:
+Casos de uso común son:
-- **base=16** is used for hex colors, character encodings etc, digits can be `0..9` or `A..F`.
-- **base=2** is mostly for debugging bitwise operations, digits can be `0` or `1`.
-- **base=36** is the maximum, digits can be `0..9` or `A..Z`. The whole latin alphabet is used to represent a number. A funny, but useful case for `36` is when we need to turn a long numeric identifier into something shorter, for example to make a short url. Can simply represent it in the numeral system with base `36`:
+- **base=16** usada para colores hex, codificación de caracteres, etc; los dígitos pueden ser `0..9` o `A..F`.
+- **base=2** mayormente usada para el debug de operaciones de bit, los dígitos pueden ser `0` o `1`.
+- **base=36** Es el máximo, los dígitos pueden ser `0..9` o `A..Z`. Aquí el alfabeto inglés completo es usado para representar un número. Un uso peculiar pero práctico para la base `36` es cuando necesitamos convertir un largo identificador numérico en algo más corto, por ejemplo para abreviar una url. Podemos simplemente representarlo en el sistema numeral de base `36`:
```js run
alert( 123456..toString(36) ); // 2n9c
```
-```warn header="Two dots to call a method"
-Please note that two dots in `123456..toString(36)` is not a typo. If we want to call a method directly on a number, like `toString` in the example above, then we need to place two dots `..` after it.
+```warn header="Dos puntos para llamar un método"
+Por favor observa que los dos puntos en `123456..toString(36)` no son un error tipográfico. Si queremos llamar un método directamente sobre el número, como `toString` del ejemplo anterior, necesitamos ubicar los dos puntos `..` tras él.
-If we placed a single dot: `123456.toString(36)`, then there would be an error, because JavaScript syntax implies the decimal part after the first dot. And if we place one more dot, then JavaScript knows that the decimal part is empty and now goes the method.
+Si pusiéramos un único punto: `123456.toString(36)`, habría un error, porque la sintaxis de JavaScript implica una parte decimal después del primer punto. Al poner un punto más, JavaScript reconoce que la parte decimal está vacía y luego va el método.
-Also could write `(123456).toString(36)`.
+También podríamos escribir `(123456).toString(36)`.
```
-## Rounding
+## Redondeo
-One of the most used operations when working with numbers is rounding.
+Una de las operaciones más usadas cuando se trabaja con números es el redondeo.
-There are several built-in functions for rounding:
+Hay varias funciones incorporadas para el redondeo:
`Math.floor`
-: Rounds down: `3.1` becomes `3`, and `-1.1` becomes `-2`.
+: Redondea hacia abajo: `3.1` se convierte en `3`, y `-1.1` se hace `-2`.
`Math.ceil`
-: Rounds up: `3.1` becomes `4`, and `-1.1` becomes `-1`.
+: Redondea hacia arriba: `3.1` torna en `4`, y `-1.1` torna en `-1`.
`Math.round`
-: Rounds to the nearest integer: `3.1` becomes `3`, `3.6` becomes `4` and `-1.1` becomes `-1`.
+: Redondea hacia el entero más cercano: `3.1` torna en `3`, `3.6` torna en `4` y `-1.1` torna en `-1`.
-`Math.trunc` (not supported by Internet Explorer)
-: Removes anything after the decimal point without rounding: `3.1` becomes `3`, `-1.1` becomes `-1`.
+`Math.trunc` (no soportado en Internet Explorer)
+: Remueve lo que haya tras el punto decimal sin redondear: `3.1` torna en `3`, `-1.1` torna en `-1`.
-Here's the table to summarize the differences between them:
+Aquí, la tabla que resume las diferencias entre ellos:
| | `Math.floor` | `Math.ceil` | `Math.round` | `Math.trunc` |
|---|---------|--------|---------|---------|
@@ -140,259 +140,260 @@ Here's the table to summarize the differences between them:
|`-1.6`| `-2` | `-1` | `-2` | `-1` |
-These functions cover all of the possible ways to deal with the decimal part of a number. But what if we'd like to round the number to `n-th` digit after the decimal?
+Estas funciones cubren todas las posibles formas de lidiar con la parte decimal de un número. Pero ¿si quisiéramos redondear al enésimo `n-th` dígito tras el decimal?
-For instance, we have `1.2345` and want to round it to 2 digits, getting only `1.23`.
+Por ejemplo, tenemos `1.2345` y queremos redondearlo a 2 dígitos obteniendo solo `1.23`.
-There are two ways to do so:
+Hay dos formas de hacerlo:
-1. Multiply-and-divide.
+1. Multiplicar y dividir.
- For example, to round the number to the 2nd digit after the decimal, we can multiply the number by `100`, call the rounding function and then divide it back.
+ Para redondear el número a dos dígitos tras el decimal, podemos multiplicarlo por `100`, llamar la función de redondeo y volverlo a dividir.
```js run
let num = 1.23456;
alert( Math.floor(num * 100) / 100 ); // 1.23456 -> 123.456 -> 123 -> 1.23
```
-2. The method [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) rounds the number to `n` digits after the point and returns a string representation of the result.
+2. El método [toFixed(n)](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Number/toFixed) redondea el número a `n` dígitos después del punto decimal y devuelve una cadena que representa el resultado.
```js run
let num = 12.34;
alert( num.toFixed(1) ); // "12.3"
```
- This rounds up or down to the nearest value, similar to `Math.round`:
+ Redondea hacia arriba o abajo al valor más cercano, similar a `Math.round`:
```js run
let num = 12.36;
alert( num.toFixed(1) ); // "12.4"
```
- Please note that result of `toFixed` is a string. If the decimal part is shorter than required, zeroes are appended to the end:
+ Ten en cuenta que el resultado de `toFixed` es una cadena. Si la parte decimal es más corta que lo requerido, se agregan ceros hasta el final:
```js run
let num = 12.34;
- alert( num.toFixed(5) ); // "12.34000", added zeroes to make exactly 5 digits
+ alert( num.toFixed(5) ); // "12.34000", con ceros agregados para dar exactamente 5 dígitos
```
- We can convert it to a number using the unary plus or a `Number()` call: `+num.toFixed(5)`.
+ Podemos convertirlo a número usando el operador unario más o llamando a `Number()`: `+num.toFixed(5)`.
-## Imprecise calculations
+## Cálculo impreciso
-Internally, a number is represented in 64-bit format [IEEE-754](https://en.wikipedia.org/wiki/IEEE_754-2008_revision), so there are exactly 64 bits to store a number: 52 of them are used to store the digits, 11 of them store the position of the decimal point (they are zero for integer numbers), and 1 bit is for the sign.
+Internamente, un número es representado en formato de 64-bit [IEEE-754](http://en.wikipedia.org/wiki/IEEE_754-1985), donde hay exactamente 64 bits para almacenar un número: 52 de ellos son usados para almacenar los dígitos, 11 para almacenar la posición del punto decimal (son cero para los enteros), y 1 bit es para el signo.
-If a number is too big, it would overflow the 64-bit storage, potentially giving an infinity:
+Si un número es demasiado grande rebasaría el almacén de 64 bit, potencialmente dando infinito:
```js run
alert( 1e500 ); // Infinity
```
-What may be a little less obvious, but happens quite often, is the loss of precision.
+Lo que puede ser algo menos obvio, pero ocurre a menudo, es la pérdida de precisión.
-Consider this (falsy!) test:
+Considera este (¡falso!) test:
```js run
alert( 0.1 + 0.2 == 0.3 ); // *!*false*/!*
```
-That's right, if we check whether the sum of `0.1` and `0.2` is `0.3`, we get `false`.
+Es así, al comprobar si la suma de `0.1` y `0.2` es `0.3`, obtenemos `false`.
-Strange! What is it then if not `0.3`?
+¡Qué extraño! ¿Qué es si no `0.3`?
```js run
alert( 0.1 + 0.2 ); // 0.30000000000000004
```
-Ouch! There are more consequences than an incorrect comparison here. Imagine you're making an e-shopping site and the visitor puts `$0.10` and `$0.20` goods into their cart. The order total will be `$0.30000000000000004`. That would surprise anyone.
+¡Ay! Hay más consecuencias que una comparación incorrecta aquí. Imagina que estás haciendo un sitio de compras electrónicas y el visitante pone `$0.10` y `$0.20` en productos en su carrito. El total de la orden será `$0.30000000000000004`. Eso sorprendería a cualquiera..
-But why does this happen?
+¿Pero por qué pasa esto?
-A number is stored in memory in its binary form, a sequence of bits - ones and zeroes. But fractions like `0.1`, `0.2` that look simple in the decimal numeric system are actually unending fractions in their binary form.
+Un número es almacenado en memoria en su forma binaria, una secuencia de bits, unos y ceros. Pero decimales como `0.1`, `0.2` que se ven simples en el sistema decimal son realmente fracciones sin fin en su forma binaria.
-In other words, what is `0.1`? It is one divided by ten `1/10`, one-tenth. In decimal numeral system such numbers are easily representable. Compare it to one-third: `1/3`. It becomes an endless fraction `0.33333(3)`.
+En otras palabras, ¿qué es `0.1`? Es un uno dividido por 10 `1/10`, un décimo. En sistema decimal es fácilmente representable. Compáralo con un tercio: `1/3`, se vuelve una fracción sin fin `0.33333(3)`.
-So, division by powers `10` is guaranteed to work well in the decimal system, but division by `3` is not. For the same reason, in the binary numeral system, the division by powers of `2` is guaranteed to work, but `1/10` becomes an endless binary fraction.
+Así, la división en potencias de diez garantizan un buen funcionamiento en el sistema decimal, pero divisiones por `3` no. Por la misma razón, en el sistema binario la división en potencias de `2` garantizan su funcionamiento, pero `1/10` se vuelve una fracción binaria sin fin.
-There's just no way to store *exactly 0.1* or *exactly 0.2* using the binary system, just like there is no way to store one-third as a decimal fraction.
+Simplemente no hay manera de guardar *exactamente 0.1* o *exactamente 0.2* usando el sistema binario, así como no hay manera de guardar un tercio en fracción decimal.
-The numeric format IEEE-754 solves this by rounding to the nearest possible number. These rounding rules normally don't allow us to see that "tiny precision loss", but it exists.
+El formato numérico IEEE-754 resuelve esto redondeando al número posible más cercano. Estas reglas de redondeo normalmente no nos permiten percibir aquella "pequeña pérdida de precisión", pero existe.
-We can see this in action:
+Podemos verlo en acción:
```js run
alert( 0.1.toFixed(20) ); // 0.10000000000000000555
```
-And when we sum two numbers, their "precision losses" add up.
+Y cuando sumamos dos números, se apilan sus "pérdidas de precisión".
-That's why `0.1 + 0.2` is not exactly `0.3`.
+Y es por ello que `0.1 + 0.2` no es exactamente `0.3`.
-```smart header="Not only JavaScript"
-The same issue exists in many other programming languages.
+```smart header="No solo JavaScript"
+El mismo problema existe en muchos otros lenguajes de programación.
-PHP, Java, C, Perl, Ruby give exactly the same result, because they are based on the same numeric format.
+PHP, Java, C, Perl, Ruby dan exactamente el mismo resultado, porque ellos están basados en el mismo formato numérico.
```
-Can we work around the problem? Sure, the most reliable method is to round the result with the help of a method [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed):
+¿Podemos resolver el problema? Seguro, la forma más confiable es redondear el resultado con la ayuda de un método. [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed):
```js run
let sum = 0.1 + 0.2;
alert( sum.toFixed(2) ); // 0.30
```
-Please note that `toFixed` always returns a string. It ensures that it has 2 digits after the decimal point. That's actually convenient if we have an e-shopping and need to show `$0.30`. For other cases, we can use the unary plus to coerce it into a number:
+Ten en cuenta que `toFixed` siempre devuelve un string. Esto asegura que tiene 2 dígitos después del punto decimal. Esto es en verdad conveniente si tenemos un sitio de compras y necesitamos mostrar `$0.30`. Para otros casos, podemos usar el + unario para forzar un número:
```js run
let sum = 0.1 + 0.2;
alert( +sum.toFixed(2) ); // 0.3
```
-We also can temporarily multiply the numbers by 100 (or a bigger number) to turn them into integers, do the maths, and then divide back. Then, as we're doing maths with integers, the error somewhat decreases, but we still get it on division:
+También podemos multiplicar temporalmente por 100 (o un número mayor) para transformarlos a enteros, hacer las cuentas, y volverlos a dividir. Como hacemos las cuentas con enteros el error se reduce, pero aún lo tenemos en la división:
```js run
alert( (0.1 * 10 + 0.2 * 10) / 10 ); // 0.3
alert( (0.28 * 100 + 0.14 * 100) / 100); // 0.4200000000000001
```
-So, multiply/divide approach reduces the error, but doesn't remove it totally.
+Entonces el enfoque de multiplicar/dividir reduce el error, pero no lo elimina por completo.
-Sometimes we could try to evade fractions at all. Like if we're dealing with a shop, then we can store prices in cents instead of dollars. But what if we apply a discount of 30%? In practice, totally evading fractions is rarely possible. Just round them to cut "tails" when needed.
+A veces podemos tratar de evitar los decimales del todo. Si estamos tratando con una tienda, podemos almacenar precios en centavos en lugar de dólares. Pero ¿y si aplicamos un descuento de 30%? En la práctica, evitar la parte decimal por completo es raramente posible. Simplemente se redondea y se corta el "rabo" decimal cuando es necesario.
-````smart header="The funny thing"
-Try running this:
+````smart header="Algo peculiar"
+Prueba ejecutando esto:
```js run
-// Hello! I'm a self-increasing number!
-alert( 9999999999999999 ); // shows 10000000000000000
+// ¡Hola! ¡Soy un número que se autoincrementa!
+alert( 9999999999999999 ); // muestra 10000000000000000
```
-This suffers from the same issue: a loss of precision. There are 64 bits for the number, 52 of them can be used to store digits, but that's not enough. So the least significant digits disappear.
+Esto sufre del mismo problema: Una pérdida de precisión. Hay 64 bits para el número, 52 de ellos pueden ser usados para almacenar dígitos, pero no es suficiente. Entonces los dígitos menos significativos desaparecen.
-JavaScript doesn't trigger an error in such events. It does its best to fit the number into the desired format, but unfortunately, this format is not big enough.
+JavaScript no dispara error en tales eventos. Hace lo mejor que puede para ajustar el número al formato deseado, pero desafortunadamente este formato no es suficientemente grande.
````
-```smart header="Two zeroes"
-Another funny consequence of the internal representation of numbers is the existence of two zeroes: `0` and `-0`.
+```smart header="Dos ceros"
+Otra consecuencia peculiar de la representación interna de los números es la existencia de dos ceros: `0` y `-0`.
-That's because a sign is represented by a single bit, so it can be set or not set for any number including a zero.
+Esto es porque el signo es representado por un bit, así cada número puede ser positivo o negativo, incluyendo al cero.
-In most cases the distinction is unnoticeable, because operators are suited to treat them as the same.
+En la mayoría de los casos la distinción es imperceptible, porque los operadores están adaptados para tratarlos como iguales.
```
-## Tests: isFinite and isNaN
+## Tests: isFinite e isNaN
-Remember these two special numeric values?
+¿Recuerdas estos dos valores numéricos especiales?
-- `Infinity` (and `-Infinity`) is a special numeric value that is greater (less) than anything.
-- `NaN` represents an error.
+- `Infinity` (y `-Infinity`) es un valor numérico especial que es mayor (menor) que cualquier otra cosa.
+- `NaN` ("No un Número") representa un error.
+=======
-They belong to the type `number`, but are not "normal" numbers, so there are special functions to check for them:
+Ambos pertenecen al tipo `number`, pero no son números "normales", así que hay funciones especiales para chequearlos:
-- `isNaN(value)` converts its argument to a number and then tests it for being `NaN`:
+- `isNaN(value)` convierte su argumento a número entonces testea si es `NaN`:
```js run
alert( isNaN(NaN) ); // true
alert( isNaN("str") ); // true
```
- But do we need this function? Can't we just use the comparison `=== NaN`? Sorry, but the answer is no. The value `NaN` is unique in that it does not equal anything, including itself:
+ Pero ¿necesitamos esta función? ¿No podemos simplemente usar la comparación `=== NaN`? Lo lamento pero la respuesta es no. El valor `NaN` es único en que no es igual a nada, incluyendo a sí mismo:
```js run
alert( NaN === NaN ); // false
```
-- `isFinite(value)` converts its argument to a number and returns `true` if it's a regular number, not `NaN/Infinity/-Infinity`:
+- `isFinite(value)` convierte su argumento a un número y devuelve `true` si es un número regular, no `NaN/Infinity/-Infinity`:
```js run
alert( isFinite("15") ); // true
- alert( isFinite("str") ); // false, because a special value: NaN
- alert( isFinite(Infinity) ); // false, because a special value: Infinity
+ alert( isFinite("str") ); // false, porque es un valor especial: NaN
+ alert( isFinite(Infinity) ); // false, porque es un valor especial: Infinity
```
-Sometimes `isFinite` is used to validate whether a string value is a regular number:
+A veces `isFinite` es usado para validar si un valor string es un número regular:
```js run
let num = +prompt("Enter a number", '');
-// will be true unless you enter Infinity, -Infinity or not a number
+// siempre true salvo que ingreses Infinity, -Infinity o un valor no numérico
alert( isFinite(num) );
```
-Please note that an empty or a space-only string is treated as `0` in all numeric functions including `isFinite`.
+Ten en cuenta que un valor vacío o un string de solo espacios es tratado como `0` en todas las funciones numéricas incluyendo `isFinite`.
-```smart header="Compare with `Object.is`"
+```smart header="Comparación con `Object.is`"
-There is a special built-in method [`Object.is`](mdn:js/Object/is) that compares values like `===`, but is more reliable for two edge cases:
+Hay un método especial incorporado [Object.is](mdn:js/Object/is) que compara valores como el `===`, pero es más confiable para dos casos extremos:
-1. It works with `NaN`: `Object.is(NaN, NaN) === true`, that's a good thing.
-2. Values `0` and `-0` are different: `Object.is(0, -0) === false`, technically that's true, because internally the number has a sign bit that may be different even if all other bits are zeroes.
+1. Funciona con `NaN`: `Object.is(NaN, NaN) === true`, lo que es una buena cosa.
+2. Los valores `0` y `-0` son diferentes: `Object.is(0, -0) === false`. `false` es técnicamente correcto, porque internamente el número puede tener el bit de signo diferente incluso aunque todos los demás sean ceros.
-In all other cases, `Object.is(a, b)` is the same as `a === b`.
+En todos los demás casos, `Object.is(a, b)` es lo mismo que `a === b`.
-This way of comparison is often used in JavaScript specification. When an internal algorithm needs to compare two values for being exactly the same, it uses `Object.is` (internally called [SameValue](https://tc39.github.io/ecma262/#sec-samevalue)).
+Esta forma de comparación se usa a menudo en la especificación JavaScript. Cuando un algoritmo interno necesita comparar que dos valores sean exactamente iguales, usa `Object.is` (internamente llamado [SameValue](https://tc39.github.io/ecma262/#sec-samevalue)).
```
-## parseInt and parseFloat
+## parseInt y parseFloat
-Numeric conversion using a plus `+` or `Number()` is strict. If a value is not exactly a number, it fails:
+La conversión numérica usando un más `+` o `Number()` es estricta. Si un valor no es exactamente un número, falla:
```js run
alert( +"100px" ); // NaN
```
-The sole exception is spaces at the beginning or at the end of the string, as they are ignored.
+Siendo la única exepción los espacios al principio y al final del string, pues son ignorados.
-But in real life we often have values in units, like `"100px"` or `"12pt"` in CSS. Also in many countries the currency symbol goes after the amount, so we have `"19€"` and would like to extract a numeric value out of that.
+Pero en la vida real a menudo tenemos valores en unidades como `"100px"` o `"12pt"` en CSS. También el símbolo de moneda que en varios países va después del monto, tenemos `"19€"` y queremos extraerle la parte numérica.
-That's what `parseInt` and `parseFloat` are for.
+Para eso sirven `parseInt` y `parseFloat`.
-They "read" a number from a string until they can't. In case of an error, the gathered number is returned. The function `parseInt` returns an integer, whilst `parseFloat` will return a floating-point number:
+Estas "leen" el número desde un string hasta que dejan de poder hacerlo. Cuando se topa con un error devuelve el número que haya registrado hasta ese momento. La función `parseInt` devuelve un entero, mientras que `parseFloat` devolverá un punto flotante:
```js run
alert( parseInt('100px') ); // 100
alert( parseFloat('12.5em') ); // 12.5
-alert( parseInt('12.3') ); // 12, only the integer part is returned
-alert( parseFloat('12.3.4') ); // 12.3, the second point stops the reading
+alert( parseInt('12.3') ); // 12, devuelve solo la parte entera
+alert( parseFloat('12.3.4') ); // 12.3, el segundo punto detiene la lectura
```
-There are situations when `parseInt/parseFloat` will return `NaN`. It happens when no digits could be read:
+Hay situaciones en que `parseInt/parseFloat` devolverán `NaN`. Ocurre cuando no puedo encontrar dígitos:
```js run
-alert( parseInt('a123') ); // NaN, the first symbol stops the process
+alert( parseInt('a123') ); // NaN, el primer símbolo detiene la lectura
```
-````smart header="The second argument of `parseInt(str, radix)`"
-The `parseInt()` function has an optional second parameter. It specifies the base of the numeral system, so `parseInt` can also parse strings of hex numbers, binary numbers and so on:
+````smart header="El segundo argumento de `parseInt(str, radix)`"
+La función `parseInt()` tiene un segundo parámetro opcional. Este especifica la base de sistema numérico, entonces `parseInt` puede también analizar cadenas de numeros hexa, binarios y otros:
```js run
alert( parseInt('0xff', 16) ); // 255
-alert( parseInt('ff', 16) ); // 255, without 0x also works
+alert( parseInt('ff', 16) ); // 255, sin 0x también funciona
alert( parseInt('2n9c', 36) ); // 123456
```
````
-## Other math functions
+## Otras funciones matemáticas
-JavaScript has a built-in [Math](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math) object which contains a small library of mathematical functions and constants.
+JavaScript tiene un objeto incorporado [Math](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math) que contiene una pequeña biblioteca de funciones matemáticas y constantes.
-A few examples:
+Unos ejemplos:
`Math.random()`
-: Returns a random number from 0 to 1 (not including 1)
+: Devuelve un número aleatorio entre 0 y 1 (no incluyendo 1)
```js run
alert( Math.random() ); // 0.1234567894322
alert( Math.random() ); // 0.5435252343232
- alert( Math.random() ); // ... (any random numbers)
+ alert( Math.random() ); // ... (cualquier número aleatorio)
```
`Math.max(a, b, c...)` / `Math.min(a, b, c...)`
-: Returns the greatest/smallest from the arbitrary number of arguments.
+: Devuelve el mayor/menor de entre una cantidad arbitraria de argumentos.
```js run
alert( Math.max(3, 5, -10, 0, 1) ); // 5
@@ -400,36 +401,36 @@ A few examples:
```
`Math.pow(n, power)`
-: Returns `n` raised the given power
+: Devuelve `n` elevado a la potencia `power` dada
```js run
- alert( Math.pow(2, 10) ); // 2 in power 10 = 1024
+ alert( Math.pow(2, 10) ); // 2 elevado a la potencia de 10 = 1024
```
-There are more functions and constants in `Math` object, including trigonometry, which you can find in the [docs for the Math](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math) object.
+Hay más funciones y constantes en el objeto `Math`, incluyendo trigonometría, que puedes encontrar en la [documentación del objeto Math](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math).
-## Summary
+## Resumen
-To write numbers with many zeroes:
+Para escribir números con muchos ceros:
-- Append `"e"` with the zeroes count to the number. Like: `123e6` is the same as `123` with 6 zeroes `123000000`.
-- A negative number after `"e"` causes the number to be divided by 1 with given zeroes. E.g. `123e-6` means `0.000123` (`123` millionths).
+- Agregar `"e"` con la cantidad de ceros al número. Como: `123e6` es `123` con 6 ceros `123000000`.
+- un número negativo después de `"e"` causa que el número sea dividido por 1 con los ceros dados:. `123e-6` significa `0.000123` (`123` millonésimos).
-For different numeral systems:
+Para sistemas numéricos diferentes:
-- Can write numbers directly in hex (`0x`), octal (`0o`) and binary (`0b`) systems.
-- `parseInt(str, base)` parses the string `str` into an integer in numeral system with given `base`, `2 ≤ base ≤ 36`.
-- `num.toString(base)` converts a number to a string in the numeral system with the given `base`.
+- Se pueden escribir números directamente en sistemas hexa (`0x`), octal (`0o`) y binario (`0b`).
+- `parseInt(str, base)` convierte un string a un entero en el sistema numérico de la `base` dada `base`, `2 ≤ base ≤ 36`.
+- `num.toString(base)` convierte un número a string en el sistema de la `base` dada.
-For converting values like `12pt` and `100px` to a number:
+Para convertir valores como `12pt` y `100px` a un número:
-- Use `parseInt/parseFloat` for the "soft" conversion, which reads a number from a string and then returns the value they could read before the error.
+- Usa `parseInt/parseFloat` para una conversión "suave", que lee un número desde un string y devuelve el valor del número que pudiera leer antes de encontrar error.
-For fractions:
+Para números con decimales:
-- Round using `Math.floor`, `Math.ceil`, `Math.trunc`, `Math.round` or `num.toFixed(precision)`.
-- Make sure to remember there's a loss of precision when working with fractions.
+- Redondea usando `Math.floor`, `Math.ceil`, `Math.trunc`, `Math.round` o `num.toFixed(precision)`.
+- Asegúrate de recordar que hay pérdida de precisión cuando se trabaja con decimales.
-More mathematical functions:
+Más funciones matemáticas:
-- See the [Math](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math) object when you need them. The library is very small, but can cover basic needs.
+- Revisa el documento del objeto [Math](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Math) cuando las necesites. La biblioteca es pequeña pero puede cubrir las necesidades básicas.
pFad - Phonifier reborn
Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies:
Alternative Proxy
pFad Proxy
pFad v3 Proxy
pFad v4 Proxy