發布於 2023-02-18

更新於 2023-02-18

程式

約1477字 (8分鐘閱讀)

[Day 10] JavaScript Math 和 toFixed() 的使用指南 - 嘗試 30 日寫文充版挑戰

Title Image

Photo by Bekky Bekks on Unsplash

前言 - Prologue

嘗試 30 天寫文充實版面 (跳過假日但是今天是補班日 ლ(́◕◞౪◟◕‵ლ) ) 不間斷更新文章的 Day 10

當我們需要進行複雜的數學運算時,JavaScript 中的 Math 對象可以派上用場。該對象提供了各種數學函數,例如 sin、cos、tan、sqrt 等,可讓我們快速完成各種計算。而當需要處理小數位數時,JavaScript 中的 toFixed() 方法則是一個非常方便的選擇。這個方法可讓我們將一個浮點數四捨五入為指定小數位數的固定小數點表示法,並返回一個新的字串。

在本指南中,我們將介紹如何使用 Math 對象和 toFixed() 方法來執行數學運算和處理小數位數,以幫助開發者更有效地開發 JavaScript 程式。

靜態屬性 - Static properties

PropertiesDescription
1Math.E自然對數的底數 (e ≈ 2.718)
2Math.LN22 的自然對數 (ln2 ≈ 0.693)
3Math.LN1010 的自然對數 (ln10 ≈ 2.303)
4Math.LOG2E以 2 為底的 e 的對數 (log2(e) ≈ 1.443)
5Math.LOG10E以 10 為底的 e 的對數 (log10(e) ≈ 0.434)
6Math.PI圓周率 (π ≈ 3.14159)
7Math.SQRT1_22 的平方根的倒數 (√½ ≈ 0.707)
8Math.SQRT22 的平方根 (√2 ≈ 1.414)

JavaScript 提供了 8 個可以作為數學屬性訪問的數學常量

常數 e 稱為自然對數的底數 (簡稱自然底數) 或歐拉數(Euler number),以瑞士數學家歐拉命名。

approximately [/əˈprɒksɪmətli/] = 大約

靜態方法 - Static methods

三角函數 (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) 的參數或回傳值的角度皆以弧度為單位。把角度乘上 (Math.PI / 180) 會得到弧度單位,將弧度除以該數則會轉換回一般所用的角度單位。

許多數學方法的精度是取決於實作方式的。這意味著不同的瀏覽器可能會得到不同的結果,甚至同一個 JS 引擎在不同的作業系統或架構上所得到的結果都有可能相異。

PropertiesDescription
1Math.abs()絕對值
2Math.acos()反餘弦值
3Math.acosh()雙曲反餘弦值
4Math.asin()反正弦值
5Math.asinh()雙曲反正弦值
6Math.atan()反正切值
7Math.atanh()雙曲反正切值
8Math.atan2()商的反正切值
9Math.cbrt()立方根值
10Math.ceil(x)不小於 x 的最小整數值
11Math.clz32()32 位整數的前導零數
12Math.cos()餘弦值
13Math.cosh()雙曲餘弦值
14Math.exp(x)ex
15Math.expm1(x)exp(x) 減去 1 的值
16Math.floor(x)不大於 x 的最大整數值
17Math.fround()最接近的單精度浮點表示形式
18Math.hypot()平方之和的平方根
19Math.imul()32 位整數乘法的結果
20Math.log(x)x 的自然對數值
21Math.log1p(x)1 + x 的自然對數值
22Math.log10(x)以 10 為底 x 的對數值
23Math.log2(x)以 2 為底 x 的對數值
24Math.max()定數值中的最大值
25Math.min()定數值中的最小值
26Math.pow()x 的 y 次方,也就是 xy
27Math.random()偽隨機值
28Math.round()四捨五入值
29Math.sign(x)x 的正負號,也就是回傳 x 的正負
30Math.sin()正弦值
31Math.sinh()雙曲正弦值
32Math.sqrt()正平方根
33Math.tan()正切值
34Math.tanh()雙曲正切值
35Math.trunc()刪除任何小數位
Math.round():四捨五入
# 整數
Math.round(10.49);  // 10
Math.round(10.51);  // 11
Math.round(-10.49); // -10
Math.round(-10.51); // -11

# 小數點後兩位
function round(num, decimal) {
  let n = (num + Number.EPSILON) * Math.pow(10, decimal);
  return Math.round(n) / Math.pow(10, decimal);
}

console.log(round(1.0149, 2)); // 1.01
console.log(round(1.0151, 2)); // 1.02
toFixed():四捨五入

toFixed() 方法使用定點表示法格式化數字。

toFixed(digits),digits 小數位 選擇性輸入。顯示數值至多少個小數點,範圍由 0 到 20 之間,執行時或可支援非常大範圍的數值。如果無輸入會默認做 0。

3.14159.toFixed(2); // 3.14
3.1.toFixed(2);     // 3.10
3.14.toFixed(2);    // 3.14
3.142.toFixed(2);   // 3.14
3.148.toFixed(2);   // 3.15

# 下面為 MDN 範例

function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}

console.log(financial(123.456));
// Expected output: "123.46"

console.log(financial(0.004));
// Expected output: "0.00"

console.log(financial('1.23e+5'));
// Expected output: "123000.00"
Math.floor():無條件捨去
# 整數
Math.floor(10.49);  // 10
Math.floor(10.51);  // 10
Math.floor(-10.49); // -11
Math.floor(-10.51); // -11
Math.floor(0.96);   // 0
Math.floor(-0.96);  // -1
Math.floor(3.21321) // 3

# 小數點後兩位
function round(num, decimal) {
  let n = (num + Number.EPSILON) * Math.pow(10, decimal);
  return Math.floor(n) / Math.pow(10, decimal);
}

console.log(round(1.0149, 2)); // 1.01
console.log(round(1.0151, 2)); // 1.01
Math.ceil():無條件進位
# 整數
Math.ceil(10.49);  // 11
Math.ceil(10.51);  // 11
Math.ceil(-10.49); // -10
Math.ceil(-10.51); // -10
Math.ceil(0.96);   // 1
Math.ceil(-0.96);  // 0
Math.ceil(3.21321) // 4

# 小數點後兩位
function round(num, decimal) {
  let n = (num + Number.EPSILON) * Math.pow(10, decimal);
  return Math.ceil(n) / Math.pow(10, decimal);
}

console.log(round(1.0149, 2)); // 1.02
console.log(round(1.0151, 2)); // 1.02
Math.trunc():去小數部分
Math.trunc(10.47)    // 10
Math.trunc(72.2012)  // 72
Math.trunc(0.96)     // 0
Math.trunc(-0.96)    // -0
Math.random():亂數
# 範圍 - 最小 ~ 最大值
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min );
}
# 範圍 - 默認 0 ~ 最大值-1 內的數值
function getRandomInt2(max) {
  return Math.floor(Math.random() * max );
}

console.log(getRandomInt(1, 3));
// Expected output: 1, 2 or 3

console.log(getRandomInt(5, 10));
// Expected output: 5, 6, 7, 8, 9 or 10

console.log(getRandomInt2(1));
// Expected output: 0

console.log(getRandomInt2(3));
// Expected output: 0, 1 or 2

console.log(Math.random());
// Expected output: a number from 0 to <1

瀏覽器支持 - Browser Support

要看瀏覽器支持的話,請參考 MDN Web Docs 網站的瀏覽器兼容性列表。

參考資料 - Reference

[1] Math - JavaScript | MDN

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math

[2] Number.prototype.toFixed() - JavaScript | MDN

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

後記 - Epilogue

當需要進行複雜的數學運算和小數位數處理時,JavaScript 中的 Math 對象和 toFixed() 方法可以派上用場。

大後天再來想下一篇要寫什麼了。(放假!!!)

[Day 10] JavaScript Math 和 toFixed() 的使用指南 - 嘗試 30 日寫文充版挑戰

https:///blog/17

作者

Kama

Read more from 程式
lightbox-image
Toggle Button - Red Pandas Icons by svgrepo.com

Copyrights © 2023 Kama, All Rights Reserved.