From a09b860f11b8483db69a8be412c66ad857d88608 Mon Sep 17 00:00:00 2001 From: hailong Date: Wed, 13 Jun 2018 11:21:51 +0800 Subject: [PATCH] 1-js/05-data-types/02-number (#114) * translate 1-sum-interface/solution.md * translate 1-sum-interface.task.md * translate 2-why-rounder-down task.md * translate 2 * translate 3-repeat-until-number/task.md * translate 3-repeat-until-number solution.md * translate 4-endless-loop-error * translate -random-min-max * translate 0-random-int-min-max * translate article.md to 334 * finish translate wait proofreading * update symbol * update some not perfect translate * Update solution.md * Update solution.md * Update task.md * Update solution.md * Update solution.md * Update task.md * Update solution.md * Update solution.md * Update task.md * Update solution.md * Update solution.md * Update task.md * Update task.md * Update solution.md * update * Update task.md * Update task.md * change space for num & word * change half punctutions to full * update * update * Update solution.md * Update solution.md * Update task.md * Update solution.md * Update task.md * Update solution.md * Update solution.md * Update solution.md * Update article.md * Update article.md * Update solution.md * Update task.md * Update solution.md * Update solution.md * Update solution.md * Update article.md * Update article.md --- .../02-number/1-sum-interface/solution.md | 4 +- .../02-number/1-sum-interface/task.md | 6 +- .../02-number/2-why-rounded-down/solution.md | 17 +- .../02-number/2-why-rounded-down/task.md | 11 +- .../3-repeat-until-number/solution.md | 7 +- .../02-number/3-repeat-until-number/task.md | 9 +- .../4-endless-loop-error/solution.md | 10 +- .../02-number/4-endless-loop-error/task.md | 4 +- .../02-number/8-random-min-max/solution.md | 11 +- .../02-number/8-random-min-max/task.md | 8 +- .../9-random-int-min-max/solution.md | 22 +- .../02-number/9-random-int-min-max/task.md | 10 +- 1-js/05-data-types/02-number/article.md | 260 +++++++++--------- 13 files changed, 186 insertions(+), 193 deletions(-) diff --git a/1-js/05-data-types/02-number/1-sum-interface/solution.md b/1-js/05-data-types/02-number/1-sum-interface/solution.md index f2c81437d9..96b2eef2cc 100644 --- a/1-js/05-data-types/02-number/1-sum-interface/solution.md +++ b/1-js/05-data-types/02-number/1-sum-interface/solution.md @@ -7,6 +7,6 @@ let b = +prompt("The second number?", ""); alert( a + b ); ``` -Note the unary plus `+` before `prompt`. It immediately converts the value to a number. +注意一元符号 `+` 在 `prompt` 前面。它会把获取的值转换成数字。 -Otherwise, `a` and `b` would be string their sum would be their concatenation, that is: `"1" + "2" = "12"`. \ No newline at end of file +否则,`a` 和 `b` 会是字符串,它们的总和就是它们的连接,即:`“1”+“2”=“12”`。 diff --git a/1-js/05-data-types/02-number/1-sum-interface/task.md b/1-js/05-data-types/02-number/1-sum-interface/task.md index 7801266402..123a44d6e1 100644 --- a/1-js/05-data-types/02-number/1-sum-interface/task.md +++ b/1-js/05-data-types/02-number/1-sum-interface/task.md @@ -2,10 +2,10 @@ importance: 5 --- -# Sum numbers from the visitor +# 来自访客的总数 -Create a script that prompts the visitor to enter two numbers and then shows their sum. +创建一个脚本,提示访问者输入两个数字,然后显示它们的总和。 [demo] -P.S. There is a gotcha with types. +提示:类型会有一个问题。 diff --git a/1-js/05-data-types/02-number/2-why-rounded-down/solution.md b/1-js/05-data-types/02-number/2-why-rounded-down/solution.md index a17a4671a1..6aa1ef7eb0 100644 --- a/1-js/05-data-types/02-number/2-why-rounded-down/solution.md +++ b/1-js/05-data-types/02-number/2-why-rounded-down/solution.md @@ -1,33 +1,32 @@ -Internally the decimal fraction `6.35` is an endless binary. As always in such cases, it is stored with a precision loss. +在 `6.35` 内部,小数部分是一个无限的二进制。在这种情况下,它存储的时候有一个精度的缺失。 -Let's see: +让我们来看看: ```js run alert( 6.35.toFixed(20) ); // 6.34999999999999964473 ``` -The precision loss can cause both increase and decrease of a number. In this particular case the number becomes a tiny bit less, that's why it rounded down. +精度缺失可能会导致数字的增加和减小。在这种特殊情况下,数字可能会变小了一点,这就是为什么它减小了。 -And what's for `1.35`? +那么 `1.35` 是怎样样的呢? ```js run alert( 1.35.toFixed(20) ); // 1.35000000000000008882 ``` -Here the precision loss made the number a little bit greater, so it rounded up. +在这里,精度缺失使得这个数字更大一些,所以这个数字变大了一些。 -**How can we fix the problem with `6.35` if we want it to be rounded the right way?** +**如果我们希望以正确的方式四舍五入,我们如何使用 `6.35` 为例来解决这个问题?** -We should bring it closer to an integer prior to rounding: +在四舍五入之前,我们应该把它接近整数: ```js run alert( (6.35 * 10).toFixed(20) ); // 63.50000000000000000000 ``` -Note that `63.5` has no precision loss at all. That's because the decimal part `0.5` is actually `1/2`. Fractions divided by powers of `2` are exactly represented in the binary system, now we can round it: +请注意 `63.5` 完全没有精度缺失。这是因为小数部分 `0.5` 实际上是 `1 / 2`。除以2的幂的分数在二进制系统中被精确地表示,现在我们可以围绕它来解决问题: ```js run alert( Math.round(6.35 * 10) / 10); // 6.35 -> 63.5 -> 64(rounded) -> 6.4 ``` - diff --git a/1-js/05-data-types/02-number/2-why-rounded-down/task.md b/1-js/05-data-types/02-number/2-why-rounded-down/task.md index 568c264805..711704ff51 100644 --- a/1-js/05-data-types/02-number/2-why-rounded-down/task.md +++ b/1-js/05-data-types/02-number/2-why-rounded-down/task.md @@ -2,21 +2,20 @@ importance: 4 --- -# Why 6.35.toFixed(1) == 6.3? +# 为什么 6.35.toFixed(1) == 6.3? -According to the documentation `Math.round` and `toFixed` both round to the nearest number: `0..4` lead down while `5..9` lead up. +根据文档 `Math.round` 和 `toFixed`,最近的数字四舍五入:`0..4` 会被舍去,而 `5..9` 会前进一位。 -For instance: +例如: ```js run alert( 1.35.toFixed(1) ); // 1.4 ``` -In the similar example below, why is `6.35` rounded to `6.3`, not `6.4`? +在下面的类似例子中,为什么 `6.35` 被四舍五入为 `6.3` 而不是 `6.4`? ```js run alert( 6.35.toFixed(1) ); // 6.3 ``` -How to round `6.35` the right way? - +如何以正确的方式来四舍五入 `6.35`? diff --git a/1-js/05-data-types/02-number/3-repeat-until-number/solution.md b/1-js/05-data-types/02-number/3-repeat-until-number/solution.md index 005116d17a..30c000b3b0 100644 --- a/1-js/05-data-types/02-number/3-repeat-until-number/solution.md +++ b/1-js/05-data-types/02-number/3-repeat-until-number/solution.md @@ -15,9 +15,8 @@ function readNumber() { alert(`Read: ${readNumber()}`); ``` -The solution is a little bit more intricate that it could be because we need to handle `null`/empty lines. +该解决方案有点复杂,可能是因为我们需要处理 null/空行。 -So we actually accept the input until it is a "regular number". Both `null` (cancel) and empty line also fit that condition, because in numeric form they are `0`. - -After we stopped, we need to treat `null` and empty line specially (return `null`), because converting them to a number would return `0`. +所以我们实际上接受输入,直到它成为“常规数字”。null(取消)和空行都适合该条件,因为在数字形式中它们是 `0`。 +在我们停止之后,我们需要专门处理 null 和空行(返回 null),因为将它们转换为数字将返回 `0`。 diff --git a/1-js/05-data-types/02-number/3-repeat-until-number/task.md b/1-js/05-data-types/02-number/3-repeat-until-number/task.md index 9b172fa8a2..1ea3e3d33e 100644 --- a/1-js/05-data-types/02-number/3-repeat-until-number/task.md +++ b/1-js/05-data-types/02-number/3-repeat-until-number/task.md @@ -2,13 +2,12 @@ importance: 5 --- -# Repeat until the input is a number +# 重复检测,直到输入是一个数字 -Create a function `readNumber` which prompts for a number until the visitor enters a valid numeric value. +创建一个函数 `readNumber`,它提示输入一个数字,直到访问者输入一个有效的数字。 -The resulting value must be returned as a number. +结果值必须作为数字返回。 -The visitor can also stop the process by entering an empty line or pressing "CANCEL". In that case, the function should return `null`. +访问者也可以通过输入空行或按“取消”来停止该过程。在这种情况下,函数应该返回 `null`。 [demo] - diff --git a/1-js/05-data-types/02-number/4-endless-loop-error/solution.md b/1-js/05-data-types/02-number/4-endless-loop-error/solution.md index 8bc55bd027..16201a3458 100644 --- a/1-js/05-data-types/02-number/4-endless-loop-error/solution.md +++ b/1-js/05-data-types/02-number/4-endless-loop-error/solution.md @@ -1,6 +1,6 @@ -That's because `i` would never equal `10`. +那是因为 `i` 永远不会等于 `10`。 -Run it to see the *real* values of `i`: +运行它以查看 `i` 的实际值: ```js run let i = 0; @@ -10,8 +10,8 @@ while (i < 11) { } ``` -None of them is exactly `10`. +他们中没有一个完全是 `10`。 -Such things happen because of the precision losses when adding fractions like `0.2`. +发生这样的事情是因为在添加像 `0.2` 这样的分数时出现了精度损失。 -Conclusion: evade equality checks when working with decimal fractions. \ No newline at end of file +结论:在处理小数部分时避免相等检查。 diff --git a/1-js/05-data-types/02-number/4-endless-loop-error/task.md b/1-js/05-data-types/02-number/4-endless-loop-error/task.md index 592ece31c0..95338c833c 100644 --- a/1-js/05-data-types/02-number/4-endless-loop-error/task.md +++ b/1-js/05-data-types/02-number/4-endless-loop-error/task.md @@ -2,9 +2,9 @@ importance: 4 --- -# An occasional infinite loop +#一个偶发的无限循环 -This loop is infinite. It never ends. Why? +这个循环是无限的。它永远不会结束。为什么? ```js let i = 0; diff --git a/1-js/05-data-types/02-number/8-random-min-max/solution.md b/1-js/05-data-types/02-number/8-random-min-max/solution.md index 348f9e34bc..562be1f62f 100644 --- a/1-js/05-data-types/02-number/8-random-min-max/solution.md +++ b/1-js/05-data-types/02-number/8-random-min-max/solution.md @@ -1,11 +1,11 @@ -We need to "map" all values from the interval 0..1 into values from `min` to `max`. +我们需要将区间 0..1 中的所有值“映射”为从最小值到最大值。 -That can be done in two stages: +这可以分两个阶段完成: -1. If we multiply a random number from 0..1 by `max-min`, then it the interval of possible values increases `0..1` to `0..max-min`. -2. Now if we add `min`, the possible interval becomes from `min` to `max`. +1. 如果我们将 0..1 的随机数乘以 `max-min`,则可能值的间隔从 0..1 增加到 `0..max-min`。 +2. 现在,如果我们添加 `min`,则可能的间隔将从 `min` 变为 `max`。 -The function: +函数实现: ```js run function random(min, max) { @@ -16,4 +16,3 @@ alert( random(1, 5) ); alert( random(1, 5) ); alert( random(1, 5) ); ``` - diff --git a/1-js/05-data-types/02-number/8-random-min-max/task.md b/1-js/05-data-types/02-number/8-random-min-max/task.md index 7037cfcbb9..ecfa3447b6 100644 --- a/1-js/05-data-types/02-number/8-random-min-max/task.md +++ b/1-js/05-data-types/02-number/8-random-min-max/task.md @@ -2,13 +2,13 @@ importance: 2 --- -# A random number from min to max +# 从最小到最大的随机数 -The built-in function `Math.random()` creates a random value from `0` to `1` (not including `1`). +用内置函数Math.random() 创建一个从 0 到 1 的随机值(不包括 1 )。 -Write the function `random(min, max)` to generate a random floating-point number from `min` to `max` (not including `max`). +编写随机函数(min,max)以生成从最小到最大(不包括最大值)的随机浮点数。 -Examples of its work: +实例: ```js alert( random(1, 5) ); // 1.2345623452 diff --git a/1-js/05-data-types/02-number/9-random-int-min-max/solution.md b/1-js/05-data-types/02-number/9-random-int-min-max/solution.md index 0950ff812f..b9c7a095e0 100644 --- a/1-js/05-data-types/02-number/9-random-int-min-max/solution.md +++ b/1-js/05-data-types/02-number/9-random-int-min-max/solution.md @@ -1,6 +1,6 @@ -# The simple but wrong solution +# 简单但错误的解决方案 -The simplest, but wrong solution would be to generate a value from `min` to `max` and round it: +最简单但错误的解决方案是从 `min` 到 `max` 生成一个值并取它四舍五入的值: ```js run function randomInteger(min, max) { @@ -11,11 +11,11 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ``` -The function works, but it is incorrect. The probability to get edge values `min` and `max` is two times less than any other. +这个函数是能起作用的,但不正确。获得边缘值 `min` 和 `max` 的概率是其他值的两倍。 -If you run the example above many times, you would easily see that `2` appears the most often. +如果你多次运行这个例子,你会很容易看到 `2` 出现的频率最高。 -That happens because `Math.round()` gets random numbers from the interval `1..3` and rounds them as follows: +发生这种情况是因为 `Math.round()` 从间隔 `1..3` 获得随机数并按如下所示进行四舍五入: ```js no-beautify values from 1 ... to 1.4999999999 become 1 @@ -23,11 +23,11 @@ values from 1.5 ... to 2.4999999999 become 2 values from 2.5 ... to 2.9999999999 become 3 ``` -Now we can clearly see that `1` gets twice less values than `2`. And the same with `3`. +现在我们可以清楚地看到 `1` 的值比 `2` 少两倍。和 `3` 一样。 -# The correct solution +# 正确的解决方案 -There are many correct solutions to the task. One of them is to adjust interval borders. To ensure the same intervals, we can generate values from `0.5 to 3.5`, thus adding the required probabilities to the edges: +这项任务有很多正确的解决方案。其中之一是调整间隔边界。为了确保相同的时间间隔,我们可以生成从 0.5 到 3.5 的值,从而将所需的概率添加到边缘: ```js run *!* @@ -41,7 +41,7 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ``` -An alternative way could be to use `Math.floor` for a random number from `min` to `max+1`: +另一种方法是使用 `Math.floor` 作为从 `min` 到 `max+1` 的随机数: ```js run *!* @@ -55,7 +55,7 @@ function randomInteger(min, max) { alert( randomInteger(1, 3) ); ``` -Now all intervals are mapped this way: +现在所有间隔都以这种方式映射: ```js no-beautify values from 1 ... to 1.9999999999 become 1 @@ -63,4 +63,4 @@ values from 2 ... to 2.9999999999 become 2 values from 3 ... to 3.9999999999 become 3 ``` -All intervals have the same length, making the final distribution uniform. +所有间隔的长度相同,所以最终能够均匀分配。所有整数出现的概率都相同了。 diff --git a/1-js/05-data-types/02-number/9-random-int-min-max/task.md b/1-js/05-data-types/02-number/9-random-int-min-max/task.md index 29341b2af0..f56cb6e71f 100644 --- a/1-js/05-data-types/02-number/9-random-int-min-max/task.md +++ b/1-js/05-data-types/02-number/9-random-int-min-max/task.md @@ -2,14 +2,14 @@ importance: 2 --- -# A random integer from min to max +#从最小到最大的随机整数 -Create a function `randomInteger(min, max)` that generates a random *integer* number from `min` to `max` including both `min` and `max` as possible values. +创建一个函数 `randomInteger(min,max)`,该函数从 `min` 到 `max` 生成随机整数,包括 `min` 和 `max` 作为可能值。 -Any number from the interval `min..max` must appear with the same probability. +来自间隔 `min..max` 的任何数字必须以相同的概率出现。 -Examples of its work: +功能示例: ```js alert( random(1, 5) ); // 1 @@ -17,4 +17,4 @@ alert( random(1, 5) ); // 3 alert( random(1, 5) ); // 5 ``` -You can use the solution of the [previous task](info:task/random-min-max) as the base. +您可以使用[上一个任务](info:task/random-min-max)的解决方案作为基础。 diff --git a/1-js/05-data-types/02-number/article.md b/1-js/05-data-types/02-number/article.md index 16e4275e60..7ea1ca174f 100644 --- a/1-js/05-data-types/02-number/article.md +++ b/1-js/05-data-types/02-number/article.md @@ -1,20 +1,20 @@ -# Numbers +# 数字类型 -All numbers in JavaScript are stored in 64-bit format [IEEE-754](http://en.wikipedia.org/wiki/IEEE_754-1985), also known as "double precision". +JavaScript 中的所有数字都以 64 位格式 [IEEE-754](http://en.wikipedia.org/wiki/IEEE_754-1985) 存储,也称为“双精度”。 -Let's recap and expand upon what we currently know about them. +让我们回顾一下并展开我们目前了解的内容。 -## More ways to write a number +## 编写数字的更多方法 -Imagine we need to write 1 billion. The obvious way is: +想象一下,我们需要写 10 亿。显而易见的方法是: ```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. +但在现实生活中,我们通常避免写一长串零,因为它很容易输入错误。另外,我们很懒。我们通常会为十亿或七十三亿写一些类似于 `1bn` 的数字,为 `7.3bn`。对于大多数人来说也是如此。 -In JavaScript, we shorten a number by appending the letter `"e"` to the number and specifying the zeroes count: +在 JavaScript 中,我们通过在数字后附加字母 "e" 来缩短数字,并指定零的数量来计数: ```js run let billion = 1e9; // 1 billion, literally: 1 and 9 zeroes @@ -22,7 +22,7 @@ let billion = 1e9; // 1 billion, literally: 1 and 9 zeroes alert( 7.3e9 ); // 7.3 billions (7,300,000,000) ``` -In other words, `"e"` multiplies the number by `1` with the given zeroes count. +换句话说,`"e"` 把数字乘以 `1` 后面跟着指定数量的 0。 ```js 1e3 = 1 * 1000 @@ -30,21 +30,21 @@ In other words, `"e"` multiplies the number by `1` with the given zeroes count. ``` -Now let's write something very small. Say, 1 microsecond (one millionth of a second): - +现在让我们写一些非常小的东西。例如:1 微秒(百万分之一秒): ```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: +就像以前一样,使用 `"e"` 可以提供帮助。如果我们想避免明确地写零,我们可以说: ```js let ms = 1e-6; // six zeroes to the left from 1 ``` -If we count the zeroes in `0.000001`, there are 6 of them. So naturally it's `1e-6`. -In other words, a negative number after `"e"` means a division by 1 with the given number of zeroes: +如果我们计算 `0.000001` 中的零,则有 6 个。所以自然是 `1e-6`。 + +换句话说,`e` 后面的负数表示除以 1 后面跟着给定数量的 0: ```js // -3 divides by 1 with 3 zeroes @@ -54,18 +54,18 @@ In other words, a negative number after `"e"` means a division by 1 with the giv 1.23e-6 = 1.23 / 1000000 (=0.00000123) ``` -### Hex, binary and octal numbers +### 十六进制,二进制和八进制数字 -[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. +[十六进制](https://en.wikipedia.org/wiki/Hexadecimal)数字在 JavaScript 中被广泛用于表示颜色,编码字符以及其他许多事物。所以很自然地,写一个更简短的方法:`0x` 然后是数字。 -For instance: +例如: ```js run alert( 0xff ); // 255 alert( 0xFF ); // 255 (the same, case doesn't matter) ``` -Binary and octal numeral systems are rarely used, but also supported using the `0b` and `0o` prefixes: +虽然二进制和八进制数字系统很少使用,但也支持使用 `0b` 和 `0o` 前缀: ```js run @@ -75,13 +75,13 @@ let b = 0o377; // octal form of 255 alert( a == b ); // true, the same number 255 at both sides ``` -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). +只有这三种进制支持这种写法。对于其他进制,我们应该使用函数 `parseInt`(我们将在本章后面看到)。 ## toString(base) -The method `num.toString(base)` returns a string representation of `num` in the numeral system with the given `base`. +方法 `num.toString(base)` 返回带有给定 `base` 的进制中 `num` 的字符串表示。 -For example: +举个例子: ```js run let num = 255; @@ -89,45 +89,45 @@ alert( num.toString(16) ); // ff alert( num.toString(2) ); // 11111111 ``` -The `base` can vary from `2` to `36`. By default it's `10`. +`base` 可以从 `2` 变到 `36`。默认情况下它是 `10`。 -Common use cases for this are: +常见的用例如下: -- **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** 用于十六进制颜色,字符编码等,数字可以是 `0..9` 或 `A..F`。 +- **base=2** 主要用于调试按位操作,数字可以是 `0` 或 `1`。 +- **base=36** 是最大值,数字可以是 `0..9` 或 `A..Z`。整个拉丁字母用来表示一个数字。对于 `36` 来说,一个有趣而有用的例子是,当我们需要将一个较长的数字标识符变成较短的时候,例如做一个简短的URL。可以简单地用基数为 `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="调用方法的两个点" +请注意 `123456..toString(36)` 中的两个点不是拼写错误。如果我们想直接在一个数字上调用一个方法,比如上面例子中的 `toString`,那么我们需要在它后面放置两个点 `..`。 -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. +如果我们放置一个点:`123456.toString(36)`,那么会出现错误,因为 JavaScript 语法暗示了第一个点之后的小数部分。如果我们再放一个点,那么 JavaScript 知道小数部分是空的,现在进入方法。 -Also could write `(123456).toString(36)`. +也可以写 `(123456).toString(36)`。 ``` -## Rounding +## 四舍五入 -One of the most used operations when working with numbers is rounding. +使用数字时最常用的操作之一是四舍五入。 -There are several built-in functions for rounding: +有几个内置函数用于舍入: `Math.floor` -: Rounds down: `3.1` becomes `3`, and `-1.1` becomes `-2`. +: 向下舍入:`3.1` 变成 `3`,`-1.1` 变成 `-2`。 `Math.ceil` -: Rounds up: `3.1` becomes `4`, and `-1.1` becomes `-1`. +: 向上舍入:`3.1` 变成 `4`,`-1.1` 变成 `-1`。 `Math.round` -: Rounds to the nearest integer: `3.1` becomes `3`, `3.6` becomes `4` and `-1.1` becomes `-1`. +: 向最近的整数舍入:`3.1` 变成 `3`, 3.6` 变成 `4`,`-1.1` 变成 `-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`(IE 浏览器不支持这个方法) +: 删除小数点后的所有内容而不舍入:`3.1` 变成 `3`,`-1.1` 变成 `-1`。 -Here's the table to summarize the differences between them: +以下是总结它们之间差异的表格: | | `Math.floor` | `Math.ceil` | `Math.round` | `Math.trunc` | |---|---------|--------|---------|---------| @@ -137,172 +137,172 @@ 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? +这些函数涵盖处理数字小数部分的所有可能方法。但是如果我们想在十进制后将数字四舍五入到 `n` 位呢? -For instance, we have `1.2345` and want to round it to 2 digits, getting only `1.23`. +例如,我们有 `1.2345`,并且想把它舍入到 2 位数,只得到 `1.23`。 -There are two ways to do so: +有两种方法可以这样做: -1. Multiply-and-divide. +1. 乘法和除法 - 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. + 例如,要将数字四舍五入到小数点后的第二个数字,我们可以将数字乘以 100,调用舍入函数,然后再将其除回 100。 ```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. 函数 [toFixed(n)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) 将点数后的数字四舍五入到 `n` 个数字并返回结果的字符串表示。 ```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`: + 这会向上或向下舍入到最接近的值,类似于 `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: + 请注意 `toFixed` 的结果是一个字符串。如果小数部分比所需要的短,则在结尾添加零: ```js run let num = 12.34; alert( num.toFixed(5) ); // "12.34000", added zeroes to make exactly 5 digits ``` - We can convert it to a number using the unary plus or a `Number()` call: `+num.toFixed(5)`. + 我们可以使用一元加号或 `Number()` 调用将其转换为数字:`+ num.toFixed(5)`。 -## Imprecise calculations +## 不精确计算 -Internally, a number is represented in 64-bit format [IEEE-754](http://en.wikipedia.org/wiki/IEEE_754-1985), 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. +在 js 内部,一个数字以 64 位格式 [IEEE-754](http://en.wikipedia.org/wiki/IEEE_754-1985) 表示,所以正好有 64 位可以存储一个数字:其中 52 个被使用存储这些数字,其中 11 个存储小数点的位置(它们对于整数为零),1 位用于符号。 -If a number is too big, it would overflow the 64-bit storage, potentially giving an infinity: +如果一个数字太大,它会溢出 64 位存储,可能会输出无穷大: ```js run alert( 1e500 ); // Infinity ``` -What may be a little less obvious, but happens quite often, is the loss of precision. +可能不那么明显,但经常会发生精度的损失。 -Consider this (falsy!) test: +考虑下这个(falsy!)测试: ```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`. +没错,如果我们检查 `0.1` 和 `0.2` 的总和是否为 `0.3`,们会得到 `false`。 -Strange! What is it then if not `0.3`? +奇怪!那么如果不是 `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 his chart. The order total will be `$0.30000000000000004`. That would surprise anyone. +哎哟!这里的错误有更大的误差。想象一下,你正在制作一个电子购物网站,访问者将 `0.10 美元` 和 `0.20 美元` 商品放入他的图表中。订单总额将是 `$ 0.30000000000000004`。这会让任何人感到惊讶。 -But why does this happen? +但为什么会发生这样的事呢? -A number is stored in memory in its binary form, a sequence of 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. +一个数字以二进制形式存储在内存中,一个 1 和 0 的序列。但是像十进制数字系统看起来很简单的 `0.1`,`0.2` 这样的分数实际上是二进制形式的无限分数。 -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)`. +换句话说,什么是 `0.1`?十分之一除以十分之一,即十分之一。在十进制数字系统中,这些数字很容易表示。将它比作三分之一:`1/3`。它变成了无尽的分数 `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. +所以,按这种用 `10` 划分可以保证在十进制系统中运行良好,但用 `3` 划分不是。出于同样的原因,在二进制数字系统中,`2` 的幂的分割保证工作,但 `1/10` 变成一个无限的二进制分数。 -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. +使用二进制系统只能存储 *0.1* 或 *0.2*,就像没有办法将三分之一存储为小数部分一样。 -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", so the number shows up as `0.3`. But beware, the loss still exists. +数字格式 IEEE-754 通过四舍五入到最接近的可能数字来解决此问题。这些舍入规则通常不允许我们看到 `极小的精确度损失`,因此数字显示为 `0.3`。但要小心,损失依然存在。 -We can see this in action: +我们可以看到这一点: ```js run alert( 0.1.toFixed(20) ); // 0.10000000000000000555 ``` -And when we sum two numbers, their "precision losses" add up. +当我们给两个数字求和时,他们的“精度损失”会加起来。 -That's why `0.1 + 0.2` is not exactly `0.3`. +这就是为什么 `0.1 + 0.2` 不等于 `0.3` 的原因。 -```smart header="Not only JavaScript" -The same issue exists in many other programming languages. +```smart header="不仅仅是 JavaScript" +许多其他编程语言也存在同样的问题。 -PHP, Java, C, Perl, Ruby give exactly the same result, because they are based on the same numeric format. +PHP, Java, C, Perl, Ruby 给出完全相同的结果,因为它们基于相同的数字格式。 ``` -Can we work around the problem? Sure, there're a number of ways: +我们能解决这个问题吗?当然,有很多方法: -1. We can 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): +1. 我们可以在特定函数的帮助下对结果进行四舍五入 [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: + 请注意 `toFixed` 总是返回一个字符串。它确保它在小数点后有 2 位数字。如果我们有电子购物并需要显示 `0.30 美元`,这实际上很方便。对于其他情况,我们可以使用一元加号将它强制为一个数字: ```js run let sum = 0.1 + 0.2; alert( +sum.toFixed(2) ); // 0.3 ``` -2. We can temporarily turn numbers into integers for the maths and then revert it back. It works like this: +2. 我们可以暂时将数字转换为数学整数,然后将其恢复。它是这样工作的: ```js run alert( (0.1 * 10 + 0.2 * 10) / 10 ); // 0.3 ``` - This works because when we do `0.1 * 10 = 1` and `0.2 * 10 = 2` then both numbers become integers, and there's no precision loss. + 这是有效的,因为当我们做 `0.1 * 10 = 1` 和 `0.2 * 10 = 2` 时,那么这两个数字就变成了整数,并且没有精度损失。 -3. If we were dealing with a shop, then the most radical solution would be to store all prices in cents and use no fractions at all. But what if we apply a discount of 30%? In practice, totally evading fractions is rarely feasible, so the solutions above help avoid this pitfall. +3. 如果我们在与一家商店打交道,那么最激进的解决方案就是将所有价格存储在美分中,并且根本不使用分数。但是,如果我们应用 30% 的折扣呢?在实践中,完全回避分数是很难实现的,所以上述解决方案有助于避免这种缺陷。 -````smart header="The funny thing" -Try running this: +````smart header="有趣的事情" +尝试运行这个: ```js run // Hello! I'm a self-increasing number! alert( 9999999999999999 ); // shows 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. +出现了同样的问题:精度的损失。该号码有 64 位,其中 52 位可用于存储数字,但这还不够。所以最不重要的数字就消失了。 -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 在这种事件中不会触发错误。它尽最大努力使数字符合所需的格式,但不幸的是,这种格式不够大到满足需求。 ```` -```smart header="Two zeroes" -Another funny consequence of the internal representation of numbers is the existence of two zeroes: `0` and `-0`. +```samrt header="两个零" +数字内部表示的另一个有趣结果是存在两个零:`0` 和 `-0`。 -That's because a sign is represented by a single bit, so every number can be positive or negative, including a zero. +这是因为一个符号由一个位表示,所以每个数字可以是正数或负数,包括零。 -In most cases the distinction is unnoticeable, because operators are suited to treat them as the same. +在大多数情况下,这种区别并不明显,因为操作员可以将它们视为相同。 ``` -## Tests: isFinite and isNaN +## 测试:isFinite 和 isNaN -Remember these two special numeric values? +还记得这两个特殊的数值吗? -- `Infinite` (and `-Infinite`) is a special numeric value that is greater (less) than anything. -- `NaN` represents an error. +- `Infinite`(和 `-Infinite`)是一个特殊的数值,比任何数值都大(小)。 +- `NaN` 代表一个错误。 -They belong to the type `number`, but are not "normal" numbers, so there are special functions to check for them: +它们属于 `数字` 类型,但不是 `普通` 数字,因此有特殊函数可以检查它们: -- `isNaN(value)` converts its argument to a number and then tests it for being `NaN`: +- `isNaN(value)` 将其参数转换为数字,然后测试它是否为 `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: + 但是我们需要这个功能吗?我们不能只使用比较 `=== NaN` 吗?对不起,但答案是否定的。值 "NaN" 是独一无二的,它不等于任何东西,包括它本身: ```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)` 将其参数转换为数字,如果是常规数字,则返回 `true`,而不是 `NaN / Infinity / -Infinity`: ```js run alert( isFinite("15") ); // true @@ -310,46 +310,46 @@ They belong to the type `number`, but are not "normal" numbers, so there are spe alert( isFinite(Infinity) ); // false, because a special value: Infinity ``` -Sometimes `isFinite` is used to validate whether a string value is a regular number: +有时 `isFinite` 用于验证字符串值是否为常规数字: ```js run let num = +prompt("Enter a number", ''); -// will be true unless you enter Infinity, -Infinity or not a number +// 结果会是 true,除非你输入无穷大,无穷大或不是数字 alert( isFinite(num) ); ``` -Please note that an empty or a space-only string is treated as `0` in all numeric functions including `isFinite`. +请注意,所有数字函数(包括 `isFinite`)中的空字符串或空格字符串均被视为 `0`。 -```smart header="Compare with `Object.is`" +```smart header="与 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: +有一种特殊的内置方法 [Object.is](mdn:js/Object/is),它可以比较 `===` 等值,但对于两种边缘情况更可靠: -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`, it rarely matters, but these values technically are different. +1. 它适用于 `NaN`: `Object.is(NaN,NaN)=== true`,这是件好事。 +2. 值 `0` 和 `-0` 是不同的:`Object.is(0,-0)=== false`,它不是很重要,但这些值在技术上是不同的。 -In all other cases, `Object.is(a, b)` is the same as `a === b`. +在所有其他情况下,`Object.is(a,b)` 与 `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)). +这种比较方式经常用于 JavaScript 规范。当内部算法需要比较两个值完全相同时,它使用 Object.is(内部称为 [SameValue](https://tc39.github.io/ecma262/#sec-samevalue))。 ``` -## parseInt and parseFloat +## parseInt 和 parseFloat -Numeric conversion using a plus `+` or `Number()` is strict. If a value is not exactly a number, it fails: +使用加号 `+` 或 `Number()` 的数字转换是严格的。如果一个值不完全是一个数字,就会失败: ```js run alert( +"100px" ); // NaN ``` -The sole exception is spaces at the beginning or at the end of the string, as they are ignored. +唯一的例外是字符串开头或结尾的空格,因为它们会被忽略。 -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. +但在现实生活中,我们经常以单位表示值,比如 CSS 中的 `"100px"` 或 `"12pt"`。在许多国家,货币符号也超过了金额,所以我们有 `"19€"`,并希望从中提取一个数值。 -That's what `parseInt` and `parseFloat` are for. +这就是 `parseInt` 和 `parseFloat` 的作用。 -They "read" a number from a string until they can. In case of an error, the gathered number is returned. The function `parseInt` returns an integer, whilst `parseFloat` will return a floating-point number: +他们从字符串中“读出”一个数字,直到他们可以。如果发生错误,则返回收集的数字。函数 `parseInt` 返回一个整数,而 `parseFloat` 将返回一个浮点数: ```js run alert( parseInt('100px') ); // 100 @@ -359,14 +359,14 @@ alert( parseInt('12.3') ); // 12, only the integer part is returned alert( parseFloat('12.3.4') ); // 12.3, the second point stops the reading ``` -There are situations when `parseInt/parseFloat` will return `NaN`. It happens when no digits could be read: +有时候 `parseInt / parseFloat` 会返回 `NaN`。一般发生在没有数字可读的情况下: ```js run alert( parseInt('a123') ); // NaN, the first symbol stops the process ``` -````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="parseInt(str, radix)` 的第二个参数" +`parseInt()` 函数有一个可选的第二个参数。它指定了数字系统的基础,因此 `parseInt` 还可以解析十六进制数字,二进制数字等字符串: ```js run alert( parseInt('0xff', 16) ); // 255 @@ -376,14 +376,14 @@ alert( parseInt('2n9c', 36) ); // 123456 ``` ```` -## Other math functions +## 其他数学函数 -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 有一个内置的 [Math](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math) 对象,包含一个数学函数和常量的小型库的对象。 -A few examples: +几个例子: `Math.random()` -: Returns a random number from 0 to 1 (not including 1) +: 返回从 0 到 1 的随机数(不包括 1) ```js run alert( Math.random() ); // 0.1234567894322 @@ -392,7 +392,7 @@ A few examples: ``` `Math.max(a, b, c...)` / `Math.min(a, b, c...)` -: Returns the greatest/smallest from the arbitrary number of arguments. +: 从任意数量的参数中返回最大/最小值。 ```js run alert( Math.max(3, 5, -10, 0, 1) ); // 5 @@ -400,38 +400,36 @@ A few examples: ``` `Math.pow(n, power)` -: Returns `n` raised the given power +: 返回经过 `n` 进制转换的 power 值 ```js run alert( Math.pow(2, 10) ); // 2 in power 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. - -## Summary - -To write big numbers: +这里有 `Math` 对象中的更多函数和常量,包括三角函数,你可以在这里找到它 [docs for the Math](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math)。 -- Append `"e"` with the zeroes count to the number. Like: `123e6` is `123` with 6 zeroes. -- A negative number after `"e"` causes the number to be divided by 1 with given zeroes. That's for one-millionth or such. +## 总结 -For different numeral systems: +写非常大的数字: -- Can write numbers directly in hex (`0x`), octal (`0o`) and binary (`0b`) systems -- `parseInt(str, base)` parses an integer from any numeral system with base: `2 ≤ base ≤ 36`. -- `num.toString(base)` converts a number to a string in the numeral system with the given `base`. +- 附加 `"e"` 来省略 0,e 后面的数字就是零的个数。就像:`123e6` 是 `123` 后面接 6 个零。 +- `"e"` 后面的负数将导致数字除以 1 后面接着给定数量的零。e-6 那是一百万分之一。 -For converting values like `12pt` and `100px` to a number: +对于不同的进制: -- 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. +- 可以在十六进制(`0x`),八进制(`0o`)和二进制(`0b`)系统中直接写入数字。 +- `parseInt(str,base)` 解析来自任何数字系统的整数,其基数为:`2≤base≤36`。 +- `num.toString(base)` 将数字转换为数字系统中具有给定 `base` 的字符串。 -For fractions: +将 `12pt` 和 `100px` 等值转换为数字: -- 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. +- 使用 `parseInt / parseFloat` 进行 `软` 转换,它从字符串中读取一个数字,然后返回错误发生前可以读取的值。 -More mathematical functions: +分数: -- 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. +- 使用 `Math.floor`,`Math.ceil`,`Math.trunc`,`Math.round` 或 `num.toFixed(precision)` 循环。 +- 请记住,使用分数时会损失精度。 +更多的数学函数: +- 需要时请参阅 [Math](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math) 对象,虽然这个文档非常小,但是它可以满足基础的要求。