JavaScript Number toLocaleString() 方法



JavaScript Number toLocaleString() 方法用於根據區域設定語言格式將數字表示為字串。區域設定語言取決於計算機上設定的區域設定。它返回一個包含此數字的語言敏感表示形式的字串。

注意:區域設定是一個帶有 BCP 47 語言標籤的字串,或者是一個這樣的字串陣列。

以下是不同國家/地區的一些區域設定列表:

  • en-IN - 表示“印度”英語的區域設定。
  • en-US - 表示“美國”英語的區域設定。
  • ar-EG - 表示“阿拉伯語”的區域設定。

語法

以下是 JavaScript Number toLocaleString() 方法的語法:

toLocaleString(locales, options)

引數

此方法接受名為“locales”和“options”的兩個引數,其中“locales”引數是可選的,如下所述:

  • locales(可選) - 它是要使用的特定語言格式。
  • options - 它是一個調整輸出格式的物件。

返回值

此方法返回根據特定於語言的格式表示給定數字的字串。

示例 1

如果向此方法傳遞任何引數,它將使用預設區域設定語言格式將數字作為字串返回。

<html>
<head>
<title>JavaScript toLocaleString() method</title>
</head>
<body>
<script>
   const number = 2345;
   document.write("Given option value = ", number);
   document.write("<br>String representation = ", number.toLocaleString());
</script>
</body>
</html>

輸出

上述程式返回新的字串表示形式為 2,345:

Given option value = 2345
String representation = 2,345

示例 2

如果我們將'fi-FI'作為可選的'locale'引數值傳遞,它將使用芬蘭語語言和約定將數字格式化為字串。

<html>
<head>
<title>JavaScript toLocaleString() method</title>
</head>
<body>
<script>
   const number = 120131;
   const locale = "fi-FI";
   document.write("Given number value = ", number);
   document.write("<br>Locale value = ", locale);
   document.write("<br>String representation(FINLAND language) = ", number.toLocaleString(locale));
</script>
</body>
</html>

輸出

上述程式使用特定語言“芬蘭”將數字值轉換為字串。

Given number value = 120131
Locale value = fi-FI
String representation(FINLAND language) = 120 131

示例 3

如果我們將'en-US'作為'locale'引數值,並將'USD'作為'option'引數值傳遞,它將使用美式英語語言和貨幣將數字格式化為字串。

<html>
<head>
<title>JavaScript toLocaleString() method</title>
</head>
<body>
<script>
   const number = 1350;
   const locale = "en-US";
   const option = {style: "currency", currency: "USD"};
   document.write("Given number value = ", number);
   document.write("<br>Locale value = ", locale);
   document.write("<br>Option value = ", option.style, ' : ', option.currency);
   document.write("<br>String representation(US) = ", number.toLocaleString(locale, option));
</script>
</body>
</html>

輸出

執行上述程式後,它將數字字串轉換為美式貨幣格式。

Given number value = 1350
Locale value = en-US
Option value = currency : USD
String representation(US) = $1,350.00
廣告