JavaScript 如何使用千位分隔符打印数字
方法1:使用Intl.NumberFormat()
- Intl.NumberFormat() 对象用于根据语言敏感的格式表示数字。它可以用于表示货币或百分比,根据指定的区域设置。
- 该对象的locales参数用于指定数字的格式。使用’en-US’区域设置指定了美国和英语的格式,其中数字在千位之间用逗号表示。
- format()方法 可以用于在指定的区域设置和格式选项下返回数字的字符串。这将在千位处使用逗号格式化数字,并返回一个带有格式化数字的字符串。
语法:
nfObject = new Intl.NumberFormat('en-US')
nfObject.format(givenNumber)
示例:
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
How to print a number with commas as thousands
separators in JavaScript?
</b>
<p>Output for '123456789': <span class="output"></span>
</p>
<button onclick="separateNumber()">Separate thousands</button>
<script type="text/javascript">
function separateNumber() {
givenNumber = 123456789;
nfObject = new Intl.NumberFormat('en-US');
output = nfObject.format(givenNumber);
document.querySelector('.output').textContent = output;
}
</script>
输出:
方法2:使用toLocaleString()
- toLocaleString()方法 用于返回一个带有数字的语言敏感表示的字符串。可选的locales参数用于指定数字的格式。
- 使用地区‘en-US’来指定该地区采用美国和英语的格式,其中千位数之间用逗号表示。这将在千位数处添加逗号,并返回一个格式化数字的字符串。
语法:
givenNumber.toLocaleString('en-US')
示例:
<h1 style="color: green">GeeksforGeeks</h1>
<b>
How to print a number with commas as thousands
separators in JavaScript?
</b>
<p>Output for '987654321': <span class="output"></span>
</p>
<button onclick="separateNumber()">
Separate thousands
</button>
<script type="text/javascript">
function separateNumber() {
givenNumber = 987654321;
output = givenNumber.toLocaleString('en-US');
document.querySelector('.output').textContent = output;
}
</script>
输出: