📜  Intl.NumberFormat (1)

📅  最后修改于: 2023-12-03 15:15:51.448000             🧑  作者: Mango

Intl.NumberFormat

The Intl.NumberFormat constructor is a built-in object in JavaScript that provides a way to format numbers for specific locales or cultures.

Basic Usage

To use Intl.NumberFormat, you first create an instance of it with the desired options:

const formatter = new Intl.NumberFormat();

This creates a formatter object that you can use to format numbers. For example:

const formattedNumber = formatter.format(12345.6789);
console.log(formattedNumber); // "12,345.679"

By default, Intl.NumberFormat formats numbers with a grouping separator (such as a comma) and a decimal separator (such as a period). The exact characters used depend on the locale of the user's browser.

Options

You can pass an object to the Intl.NumberFormat constructor to specify options for the formatting:

const formatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
});

The style option determines the general format of the number. Possible values are:

  • "decimal": Formats the number using only digits, with a decimal point and optional grouping separator.
  • "currency": Formats the number as a currency value, with a symbol and optional currency code.
  • "percent": Formats the number as a percent value, with a percent sign and optional multiplication by 100.
  • "unit": Formats the number as a unit value, with a symbol and optional display of quantity.

The currency option is required when style is set to "currency". It specifies the currency code or symbol to use.

The locale option specifies the locale or culture to use for the formatting. It is set to the user's browser locale by default.

Custom Formatting

You can customize the formatting of a Intl.NumberFormat instance by setting its properties:

const formatter = new Intl.NumberFormat("en-US");
formatter.minimumFractionDigits = 2;
formatter.maximumFractionDigits = 3;
formatter.minimumIntegerDigits = 5;

These properties control the minimum and maximum number of digits to display after and before the decimal separator.

Conclusion

Whether you need to format numbers as decimals, currency, percentages, or units, Intl.NumberFormat provides an easy and flexible way to do so for a wide range of locales and cultures.