Question

How to Format Numbers as Currency Strings in JavaScript

javascriptformattingcurrencynumber-formatting

Question

I want to format a price in JavaScript. I need a function that takes a floating-point number as an argument and returns a string like this:

"$ 2,500.00"

How can I do this?

Short Answer

By the end of this page, you will understand how to turn JavaScript numbers into currency strings, including adding a currency symbol, thousands separators, and fixed decimal places. You will also learn why Intl.NumberFormat is usually the best modern solution, and when simpler approaches like toFixed() may still be useful.

Concept

Formatting a number as currency means converting a raw numeric value such as 2500 or 2500.5 into a human-friendly string such as $2,500.00.

In JavaScript, this usually involves three separate formatting tasks:

  • adding a currency symbol like $
  • showing the correct number of decimal places, usually 2 for many currencies
  • inserting thousands separators like commas

This matters because raw numbers are fine for calculations, but not ideal for display. Users expect prices, totals, invoices, and reports to be clearly formatted.

There are two common approaches in JavaScript:

  1. Manual formatting using methods like toFixed() and string manipulation
  2. Built-in international formatting using Intl.NumberFormat

For real applications, Intl.NumberFormat is usually the best choice because:

  • it handles commas and decimals correctly for different locales
  • it supports many currencies
  • it avoids a lot of custom string logic
  • it is easier to maintain

For example, the same number may be displayed differently depending on region:

  • US: $2,500.00
  • Germany: 2.500,00 €
  • Japan: ¥2,500

So the main idea is: store values as numbers, but format them as strings only when displaying them to users.

Mental Model

Think of a number as the raw value inside a calculator, and currency formatting as the label you attach when presenting the result to a person.

The calculator only cares about the value:

2500

But a user wants a nicely printed price tag:

$2,500.00

So formatting is like packaging a plain item before putting it on a store shelf. The value stays numeric internally, but the displayed version becomes easier to read.

Take Quiz

Syntax and Examples

A simple modern solution uses Intl.NumberFormat.

function formatCurrency(amount) {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD"
  }).format(amount);
}

console.log(formatCurrency(2500));
console.log(formatCurrency(2500.5));
console.log(formatCurrency(2500.99));

Output:

$2,500.00
$2,500.50
$2,500.99

How it works

  • en-US tells JavaScript to use US-style number formatting
  • style: "currency" means the output should be formatted as money
  • currency: "USD" selects US dollars

Simpler manual approach

If you only need a quick fixed format and do not care about locale differences, you can do this:

function formatCurrency(amount) {
  return "$ " + amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

console.log(formatCurrency(2500));

Output:

$ 2,500.00

Explanation of the manual version

  • toFixed(2) converts the number to a string with exactly 2 decimal places
  • the replace(...) adds commas between groups of three digits
  • "$ " + ... adds the currency symbol and a space

This works, but Intl.NumberFormat is more reliable for real projects.

Step by Step Execution

Consider this example:

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

const result = formatter.format(2500.5);
console.log(result);

Step by step:

  1. JavaScript creates a formatter object with US number rules.
  2. style: "currency" tells it to format values as money.
  3. currency: "USD" tells it to use the US dollar format.
  4. formatter.format(2500.5) converts the number 2500.5 into a formatted string.
  5. The result becomes:
"$2,500.50"

Trace with manual formatting

const amount = 2500.5;
const fixed = amount.toFixed(2);
const withCommas = fixed.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
const result = "$ " + withCommas;

console.log(result);

Step by step:

  1. amount is 2500.5
  2. toFixed(2) turns it into the string:
"2500.50"
  1. replace(...) inserts a comma:
"2,500.50"
  1. Adding "$ " gives:
"$ 2,500.50"

Real World Use Cases

Currency formatting is used in many everyday programming tasks:

  • E-commerce: showing product prices, cart totals, discounts, and taxes
  • Finance dashboards: displaying account balances, spending summaries, and revenue
  • Invoices and receipts: formatting totals for printable or downloadable documents
  • Admin panels: showing order values, payouts, refunds, and reports
  • APIs and frontends: keeping numbers raw in data, then formatting them only in the UI

Example in a shopping cart:

const subtotal = 2499.9;
const tax = 125.45;
const total = subtotal + tax;

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

console.log("Subtotal:", usd.format(subtotal));
console.log("Tax:", usd.format(tax));
console.log("Total:", usd.format(total));
Take Quiz

Real Codebase Usage

In real projects, developers usually avoid manual currency string building unless they have a very specific formatting requirement.

Common patterns include:

Reusing one formatter

Creating a formatter once is better than rebuilding it repeatedly.

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

function formatPrice(value) {
  return usdFormatter.format(value);
}

Guard clauses for invalid input

function formatPrice(value) {
  if (typeof value !== "number" || Number.isNaN(value)) {
    return "$0.00";
  }

  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD"
  }).format(value);
}

Formatting only at display time

Keep numeric values as numbers while calculating:

const items = [19.99, 5.5, 100];
const total = items.reduce((sum, price) => sum + price, 0);

console.log(total); // number for calculations
console.log(formatPrice(total)); // string for display

Mapping values for UI output

const prices = [10, 2500, 99.95];
const formatted = prices.map(price => usdFormatter.format(price));

console.log(formatted);

This is common in tables, product lists, invoices, and dashboards.

Common Mistakes

Here are common beginner mistakes when formatting currency in JavaScript.

1. Using strings instead of numbers

Broken example:

const price = "2500.5";
console.log(price.toFixed(2));

This fails because toFixed() is a number method.

Fix:

const price = Number("2500.5");
console.log(price.toFixed(2));

2. Formatting too early

Broken example:

const price = "$2,500.00";
const total = price + 100;
console.log(total);

This creates string concatenation, not math.

Fix:

const price = 2500;
const total = price + 100;
console.log(total);

Format only when displaying:

console.log(formatCurrency(total));

3. Assuming commas are the same everywhere

Broken idea:

  • hardcoding commas and periods for every user

Different regions use different separators. Prefer Intl.NumberFormat for international apps.

4. Forgetting that toFixed() returns a string

const value = 12.345;
const fixed = value.toFixed(2);

console.log(fixed); // "12.35"
console.log(typeof fixed); // string

If you need to keep doing math, stay with numbers until the end.

5. Rebuilding complex formatting logic manually

Manual regex solutions can work, but they are easier to get wrong for edge cases like:

  • negative values
  • very large numbers
  • different currencies
  • localization rules

Use built-in formatting when possible.

Comparisons

ApproachBest forProsCons
Intl.NumberFormatReal applicationsLocale-aware, supports currencies, readableSlightly more setup
toFixed() onlySimple decimal formattingEasy to useNo commas, no currency rules
toFixed() + regexQuick custom formatWorks for simple fixed outputManual, less flexible, locale-unaware

toFixed() vs Intl.NumberFormat

const amount = 2500.5;

console.log(amount.toFixed(2));
// "2500.50"

console.log(new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD"
}).format(amount));
// "$2,500.50"

Use toFixed() when you only need decimal rounding.

Use Intl.NumberFormat when you need real display formatting.

Take Quiz

Cheat Sheet

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

formatter.format(2500);   // "$2,500.00"
formatter.format(99.5);   // "$99.50"
formatter.format(-12.75); // "-$12.75"
// Reusable function
function formatCurrency(amount) {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: "USD"
  }).format(amount);
}
// Simple manual approach
function formatCurrency(amount) {
  return "$ " + amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Rules to remember

  • Keep values as numbers for calculations
  • Format only when displaying to users
  • toFixed(2) returns a string
  • Intl.NumberFormat is better for locale-aware currency formatting
  • Reuse formatter objects when formatting many values

Common edge cases

  • negative values: -25.5
  • zero: 0
  • string input: convert with Number(...) first
  • invalid input: check with Number.isNaN(...)

FAQ

How do I format a number as dollars in JavaScript?

Use Intl.NumberFormat:

new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD"
}).format(2500);

What is the best way to format currency in JavaScript?

For most applications, Intl.NumberFormat is the best choice because it is built in, reliable, and locale-aware.

Can I format currency with commas and two decimals manually?

Yes. You can use toFixed(2) and a regex to add commas, but this is less flexible than Intl.NumberFormat.

Why does toFixed() not add commas?

toFixed() only controls decimal places. It does not apply thousands separators or currency symbols.

Does Intl.NumberFormat work for other currencies?

Yes. You can change the locale and currency code.

new Intl.NumberFormat("en-GB", {
  style: "currency",
  currency: "GBP"
}).format(2500);

Should I store prices as formatted strings?

No. Store prices as numbers for calculations, and convert them to formatted strings only when displaying them.

How do I handle invalid values before formatting?

Validate the input first:

if (typeof value !== "number" || Number.isNaN(value)) {
  return "$0.00";
}
Take Quiz

Mini Project

Description

Build a small receipt formatter in JavaScript that takes a list of product prices and prints a clean invoice summary. This demonstrates real-world currency formatting because most apps need to show individual prices, subtotals, and totals clearly.

Goal

Create a reusable receipt function that formats each price in US dollars and shows the total.

Requirements

  1. Create an array of product prices as numbers.
  2. Format each price as a US currency string.
  3. Calculate the total using numeric values.
  4. Display both the item prices and the formatted total.
Take Quiz

Keep learning

Related questions

View more