Home > Web Front-end > JS Tutorial > How Can I Format Numbers as Currency Strings in JavaScript?

How Can I Format Numbers as Currency Strings in JavaScript?

Barbara Streisand
Release: 2024-12-24 11:26:20
Original
942 people have browsed it

How Can I Format Numbers as Currency Strings in JavaScript?

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:

  1. Initialize the Number Formatter:
const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});
Copy after login
  • '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.
  1. Apply the Formatting:
const formattedPrice = formatter.format(amount);
Copy after login
  • '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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template