Files
lucia-frontend/src/module/shortScaleNumber.js
2023-09-19 17:53:24 +08:00

20 lines
652 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 數量單位轉換,輸出 k m b t 數值。
* @param {number} number
* @returns {string}
*/
export default function shortScaleNumber(number) {
const abbreviations = ["", "k", "m", "b", "t"];
let index = 0;
let num = number;
// 確保在轉換數字時,不會超出索引範圍。如果 index 已經達到了最後一個單位縮寫t那麼我們就不再進行轉換以免超出數組的範圍。
while (num >= 1000 && index < abbreviations.length - 1) {
num /= 1000;
index++;
}
// 使用 Math.ceil 來無條件進位
num = Math.ceil(num * 10) / 10;
return num + abbreviations[index] + " " ;
}