如何在 JavaScript 中列印帶逗號作為千位分隔符的數字?


在本教程中,我們將瞭解一些在 JavaScript 中列印帶逗號作為千位分隔符的數字的方法,並對它們進行比較以瞭解哪種方法在給定上下文中更合適。

為什麼要進行數字格式化?在英語中,逗號用於分隔大於 999 的數字。德國使用點作為千位分隔符。瑞典使用空格。分隔符在從右起每三位數字後新增。

讓我們簡要介紹一下這些方法。

使用 toLocaleString() 方法

在這裡,內建的區域設定字串方法根據國家/地區本地化數字格式。

語法

使用者可以按照以下語法操作。

number.toLocaleString(locale)

這裡,number 是我們將用逗號分隔的數字。

引數

  • locale − 國家/地區的區域設定程式碼。對於美國,它是“en-US”。“en”是英語,“US”是美國。其他示例包括 en-GB、hi-EN 和 ar-EG。hi-EN 在每兩位數字後使用逗號。

示例

在此程式中,toLocaleString() 返回輸入的帶逗號分隔的數字。

<html> <body> <p id="inp"></p> <p id="out"></p> <script> const num = 1234567890; document.getElementById("inp").innerHTML = "Input : " + num; const result = num.toLocaleString('en-US'); document.getElementById("out").innerHTML = "Output: " + result; </script> </body> </html>

使用 Intl.NumberFormatter() 物件

Intl 是 JavaScript 中的國際化名稱空間。語言敏感的數字格式化是此方法的用途之一。

語法

使用者可以按照以下語法操作。

new Intl.NumberFormat()
new Intl.NumberFormat(locale)
new Intl.NumberFormat(locale, options)

這裡,Intl 指的是國際化。

引數

  • locale − 區域設定程式碼。例如,“en-IN”、“de-DE”、“ja-JP”。

  • options − 有許多可用的選項,例如 style、currency 等。

示例

當用戶點選按鈕時,Intl 物件將格式化數字並顯示輸出。

<html> <body> <p>Print a number with a commas separator using Intl.NumberFormat</p> <p id="inp"></p> <p id="out"></p> <script> const num = 1234567890; document.getElementById("inp").innerHTML = "Input : " + num; const result = Intl.NumberFormat('en-US').format(num); document.getElementById("out").innerHTML = "Output: " + result; </script> </body> </html>

使用正則表示式

我們可以使用正則表示式編寫程式碼來格式化數字。

語法

使用者可以按照以下語法操作。

number.toString().split(".");
number.replace(replace, ",");

這裡給出了示例中使用的字串分割和替換語法。

演算法

  • 步驟 1 − 將數字轉換為字串。

  • 步驟 2 − 分割成數字和可能的十進位制部分。

  • 步驟 3 − 使用正則表示式查詢並在數字中新增千位分隔符(3 位數字組)。

  • 步驟 4 − 用點分隔數字和小數部分。

示例

在此示例中,輸入使用自定義正則表示式分組為三位數字。

<html> <body> <h3>Print a number with a commas separator using regex</h3> <p id="regxInp"></p> <div id="regxWrap"> <p>Click the below button</p> <button onclick="regxDoFormat()">Click Me</button> </div> <p id="regxOut"></p> <script> const regxNum = 192837.4650; var regxInpEl = document.getElementById("regxInp"); var regxOutEl = document.getElementById("regxOut"); var regxBtnWrapEl = document.getElementById("regxWrap"); regxInpEl.innerHTML = "Input = " + regxNum; function regxDoFormat() { function formatNum(n) { var splits = n.toString().split("."); const numSplit = splits[0]; const decimalSplit = splits[1]; const thousands = /\B(?=(\d{3})+(?!\d))/g; return numSplit.replace(thousands, ",") + (decimalSplit ?"." + decimalSplit : ""); } const regxFormt = formatNum(regxNum); regxOutEl.innerHTML = "Output = " + regxFormt; regxBtnWrapEl.style.display = "none"; } </script> </body> </html>

透過建立自定義函式

這裡我們編寫了自定義程式碼,透過檢查小數位數和符號來對數字進行逗號分隔。

語法

number.toString().includes('.); number.toString().split('.')[0];
for (initialize; condition; loop control)
{}

這裡給出了示例中使用的字串操作和迴圈的語法。

演算法

  • 檢查小數點和數字符號。

  • 移除符號,迴圈遍歷,並相應地將逗號新增到 3 位數字組中。

  • 添加回符號並顯示輸出。

示例

這裡,負浮點數輸入根據上述演算法由自定義程式碼處理,並獲得所需的輸出。

<html> <body> <h3>Print a number with a commas separator using custom code</h3> <p id="custInp"></p> <div id="custWrap"> <p>Click this button</p> <button onclick="custDoFormat()">Click Me</button> </div> <p id="custOut"></p> <script> let custNum = -987654.4650; var custInpEl = document.getElementById("custInp"); var custOutEl = document.getElementById("custOut"); var custBtnWrapEl = document.getElementById("custWrap"); custInpEl.innerHTML = "Input = " + custNum; function custDoFormat() { function addComma(numVal) { // remove numSign var numSign = 1; if (numVal < 0) { numSign = -1; numVal = -numVal; } // trim the decimal point let num = numVal.toString().includes('.') ? numVal.toString().split('.')[0] : numVal.toString(); let len = num.toString().length; let numResult = ''; let numCount = 1; for (let i = len - 1; i >= 0; i--) { numResult = num.toString()[i] + numResult; if (numCount % 3 === 0 && numCount !== 0 && i !== 0) { numResult = ',' + numResult; } numCount++; } // include number after decimal point if (numVal.toString().includes('.')) { numResult = numResult + '.' + numVal.toString().split('.')[1]; } // return numResult with numSign return numSign < 0 ? '-' + numResult : numResult; } let custFormt = addComma(custNum); custOutEl.innerHTML = "Output = " + custFormt; custBtnWrapEl.style.display = "none"; } </script> </body> </html>

本文討論了三種在 JavaScript 中列印帶逗號作為千位分隔符的數字的方法。

locale 字串和 Intl 數字格式化方法必須首先查詢 JavaScript 引擎選擇的本地化。然後才會進行格式化。

正則表示式和字串替換方法比 toLocaleString() 方法更快。當有大量格式化請求時,您可以選擇此方法。

更新於: 2022 年 10 月 20 日

7K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告