Numbers
More ways to write a number
在實際使用大數字的時候,我們會用縮寫,像是 10 億會寫成 1bn,在程式裡也可以使用縮寫。
let billion = 1e9; // 1 billion, literally: 1 and 9 zeroes
alert( 7.3e9 ); // 7.3 billions (7,300,000,000)
1e3 = 1 * 1000
1.23e6 = 1.23 * 1000000
let ms = 0.000001;
let ms = 1e-6; // six zeroes to the left from 1
// -3 divides by 1 with 3 zeroes
1e-3 = 1 / 1000 (=0.001)
// -6 divides by 1 with 6 zeroes
1.23e-6 = 1.23 / 1000000 (=0.00000123)Hex, binary and octal numbers
hex 在 JavaScript 被廣泛應用,簡短的縮寫 0x + number 。
toString(base)
num.toString(base) 方法可以將 num 返回 string 用 base 數字系統。
base = 16,16進位,返回 0-9 a-f。
base = 2,2進位,返回 0-1。
base = 36,36進位,返回 0-9 a-z。
Two dots to call a method
如果要對數字直接使用方法要用 .. 如果使用 . JavaScript 會認為使用小數點會造成錯誤。
Rounding
Math.floor:無條件退位
Math.ceil:無條件進位
Math.round:四捨五入
Math.trunc (not supported by Internet Explorer):無條件捨去
Math.floor
Math.ceil
Math.round
Math.trunc
3.1
3
4
3
3
3.6
3
4
4
3
-1.1
-2
-1
-1
-1
-1.6
-2
-1
-2
-1
以上都是進位到整數的方法,若需要盡味道特定小數點後幾位,有 2 種方法:
Multiply-and-divide.
toFixed(n)方法四捨五入數字返回 string 在用 Number()、+返回數字。
Imprecise calculations
數字用 64-bit 系統儲存,52-bit 用來儲存數字,11-bit 儲存小數點,1-bit 儲存正負符號。
The funny thing
Tests: isFinite and isNaN
number 類型有 2 個特別的值 Infinity NaN 需要特別的方法檢測他們。
isNaN(value)轉換參數為 number 檢測是否為 NaN,返回布林值。isFinite(value)轉換參數為 number 檢測是否為 Infinity ,返回布林值。
parseInt and parseFloat
通常在類型轉換的時候數字後有單位,像是 '100px'、'12pt',這時要使用 parseInt and parseFloat。
Other math functions
Math.random()隨機產生介於 0-1 的數字,不包含 1。Math.max(a, b, c...)/Math.min(a, b, c...)返回最大 / 最小的數字。Math.pow(n, power)返回數字的次方
Last updated
Was this helpful?