JavaScript Number toLocaleString() 方法
JavaScript Number toLocaleString() 方法用于将数字表示为字符串,并使用区域设置语言的格式。区域设置语言取决于您计算机上设置的语言环境。它返回一个包含该数字的语言敏感表示形式的字符串。
注意: Locales 是一个带有 BCP 47 语言标签的字符串,或一个包含此类字符串的数组。
以下是不同国家/地区部分语言环境的列表 -
-
en-US - 表示"美国"英语的语言环境。
- ar-EG - 表示"阿拉伯语"语言的语言环境。
语法
以下是 JavaScript Number toLocaleString() 方法的语法 -
toLocaleString(locales, options)
参数
此方法接受两个名为"locales"和"options"的参数,其中"locales"参数是可选的,如下所述 -
- locales(可选) - 指定要使用的特定语言格式。
- options - 一个用于调整输出格式的对象。
返回值
此方法根据特定语言的格式返回表示给定数字的字符串。
示例 1
如果此方法未传递no参数,则使用默认语言环境的语言格式返回number字符串。
<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>
输出
上述程序使用特定语言"FINLAND"将数字值转换为字符串。
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

