# Intl.NumberFormat

The `Intl.NumberFormat` object enables language-sensitive number formatting. It allows you to easily format numbers as currency, percentages, or with specific units, respecting the user's locale.

## 1. Basic Usage

The constructor takes two optional arguments: `locales` and `options`.

```javascript
const number = 123456.789;

// US English
console.log(new Intl.NumberFormat('en-US').format(number));
// "123,456.789"

// German (uses comma as decimal separator)
console.log(new Intl.NumberFormat('de-DE').format(number));
// "123.456,789"

// India
console.log(new Intl.NumberFormat('en-IN').format(number));
// "1,23,456.789"
```

## 2. Currency Formatting

You can format numbers as currency. You must specify the `currency` code (e.g., 'USD', 'EUR').

```javascript
const price = 149.99;

const formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
});

console.log(formatter.format(price)); // "$149.99"

const euroFormatter = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR',
});

console.log(euroFormatter.format(price)); // "149,99 €"
```

## 3. Unit Formatting

You can format numbers with units (e.g., liters, meters, miles per hour).

```javascript
const speed = 50;

const formatter = new Intl.NumberFormat('en-US', {
  style: 'unit',
  unit: 'mile-per-hour',
});

console.log(formatter.format(speed)); // "50 mph"
```

## 4. Percentages

```javascript
const percent = 0.25;

const formatter = new Intl.NumberFormat('en-US', {
  style: 'percent',
});

console.log(formatter.format(percent)); // "25%"
```

## 5. Notation (Compact & Scientific)

Useful for large numbers.

```javascript
const views = 1500000;

// Compact (Short)
console.log(new Intl.NumberFormat('en-US', {
  notation: 'compact',
  compactDisplay: 'short'
}).format(views));
// "1.5M"

// Compact (Long)
console.log(new Intl.NumberFormat('en-US', {
  notation: 'compact',
  compactDisplay: 'long'
}).format(views));
// "1.5 million"

// Scientific
console.log(new Intl.NumberFormat('en-US', {
  notation: 'scientific'
}).format(views));
// "1.5E6"
```

## 6. `formatToParts`

If you need to access specific parts of the formatted string (like the currency symbol or the integer part) separately.

```javascript
const formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
const parts = formatter.formatToParts(123.45);

console.log(parts);
/*
[
  { type: "currency", value: "$" },
  { type: "integer", value: "123" },
  { type: "decimal", value: "." },
  { type: "fraction", value: "45" }
]
*/
```

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/intl-datetimeformat]]