1. Use the Intl.NumberFormat constructor
This is the most common way to format amounts in JavaScript. Intl.NumberFormat()
The constructor accepts two parameters: locale and options. The locale is the language and locale for which amounts are formatted. Options are a set of properties that control the formatting of amounts. For example, you can use the style attribute to specify the currency format, and the currency attribute to specify the currency in which to format the amount.
const amount = 1234567.89;
const locale = "en-US";
const options = {
style: "currency",
currency: "USD",
};
const formattedAmount = new Intl.NumberFormat(locale, options).format(amount);
console.log(formattedAmount); //$1,234,567.89
2. Use the Number.prototype.toLocaleString method
To format amounts, JavaScript's toLocaleString()
method . This method converts a number to a localized string representation, and can specify formats such as currency symbols, decimal points, and thousands separators.
code show as below:
-
Dollar
const amount = 1234567.89; const formattedAmount = amount.toLocaleString("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(formattedAmount); //$1,234,567.89
-
RMB
const amount = 1234567.89; const formattedAmount = amount.toLocaleString("zh-CN", { style: "currency", currency: "CNY", minimumFractionDigits: 2, maximumFractionDigits: 2, }); console.log(formattedAmount);
In this example, a numeric amount
variable toLocaleString()
is converted to a localized string representation using the method, and the following format is specified:
style: 'currency'
Indicates that the amount is displayed in currency format.currency: 'USD'
Indicates the use of the dollar sign as the currency symbol.minimumFractionDigits: 2
Indicates that at least two decimal places are reserved.maximumFractionDigits: 2
Indicates to keep up to two decimal places.
In this way, amount formatting effects can be quickly and easily implemented using JavaScript. It should be noted that toLocaleString()
the method may be different in different browsers and operating systems, and compatibility testing and compatibility processing are required.
3. Use template string + Number.prototype.toFixed + regular replacement
const amount = 1234567.89;
const formattedAmount = `¥${amount
.toFixed(2)
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
console.log(formattedAmount);
In this example, the amount is toFixed
kept to two decimal places, the thousands separator is added by regular replacement, and then the template string is used for splicing.