JavaScript 如何将数字格式化为货币字符串
一个以货币形式表示的数字会产生影响,并且更易读,这就是将数字格式化为货币的原因。例如,一个数字,假设为 100000 ,当表示为 $100,000.00 时,可以很容易理解它代表一个货币值,且以 USD 为货币单位。不同的国家有不同的货币,以及不同的展示货币值的约定。例如,美国遵循国际编号系统来表示 USD ,而印度遵循印度编号系统来表示 INR 。
语法:
Intl.NumberFormat('en-US', {style: 'currency', currency: 'target currency'})
.format(monetary_value);
说明: 此处使用“en-INR”和“en-US”作为区域设置,可以在此处找到所有区域设置的列表,并且此处使用的货币是“INR”和“USD”,但支持所有标准货币。选择不同的区域设置和货币将根据您的货币值进行格式化。
示例1:
<!DOCTYPE html>
<html>
<head>
<title>
Formatting number in currency string
</title>
</head>
<body>
<center>
<h1 style="color:green;">GeeksforGeeks</h1>
<h4>
Formatting 4800 as INR
</h4>
<script>
var format = new Intl.NumberFormat('en-INR', {
style: 'currency',
currency: 'INR',
minimumFractionDigits: 2,
});
// for 4800 INR
document.write(format.format(4800));
</script>
<center>
</body>
</html>
输出:

示例2:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<title>Currency format</title>
<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<!-- End of CDN -->
</head>
<body>
<center>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h4>
Format numbers as currency string in JavaScript
</h4>
<b>Example 1: Locale: 'en-IN' Currency: 'INR'</b>
<p>Course ABC Fees: 783984.356 (Formatting Not Used)</p>
<p>Course ABC Fees:
<span class="currency-inr">783984.356</span>
(Formatting Used)
</p>
<b>Example 2: Locale: 'en-US' Currency: 'USD'</b>
<p>Course ABC Fees: 783984.356 (Formatting Not Used)</p>
<p>Course ABC Fees:
<span class="currency-usd">783984.356</span>
(Formatting Used)
</p>
<script type="text/javascript">
('.currency-inr').each(function() {
var monetary_value =(this).text();
var i = new Intl.NumberFormat('en-IN', {
style: 'currency',
currency: 'INR'
}).format(monetary_value);
(this).text(i);
});
('.currency-usd').each(function() {
var monetary_value = (this).text();
var i = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(monetary_value);
(this).text(i);
});
</script>
</center>
</body>
</html>
输出:

注意: 我们使用的是ECMAScript国际化API(Intl对象)用于格式化目的,它属于JavaScript标准内建对象的一部分,并使用jQuery进行DOM操作。
极客教程