Formatting Numbers as Currency Strings in JavaScript
To format a price in JavaScript as a currency string, such as "$ 2,500.00", you can utilize the Intl.NumberFormat function provided by the Internationalization API.
Implementation:
- Initialize the Number Formatter:
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
});
- 'en-US' specifies the locale as English (United States).
- 'style' sets the formatting style as 'currency'.
- 'currency' denotes the currency code, such as 'USD' for US dollars.
- Apply the Formatting:
const formattedPrice = formatter.format(amount);
- 'amount' represents the floating-point value to be formatted.
- 'formattedPrice' returns the formatted currency string.
Customization Options:
You can further customize the formatting by utilizing additional parameters, such as:
-
minimumFractionDigits: Specify the minimum number of decimal places to display (e.g., minimumFractionDigits: 0 for whole numbers only).
-
maximumFractionDigits: Specify the maximum number of decimal places to display (e.g., maximumFractionDigits: 2 for two decimal places).
-
trailingZeroDisplay: Control the display of trailing zeros (e.g., 'stripIfInteger' to remove zeros when the input is a whole number).
By leveraging Intl.NumberFormat, you can easily format numbers as currency strings in a locale-aware manner.
The above is the detailed content of How Can I Format Numbers as Currency Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn