How Do You Format Numbers as Currency Strings in JavaScript?

“Format numbers as currency strings in JavaScript” is essential for creating user-friendly applications. Understanding this topic helps solve problems like displaying prices or financial data clearly and accurately. By mastering these skills, developers can enhance their apps’ functionality. Keep reading to discover how to format numbers effectively and impress your users.

Basic Method: Using toLocaleString()

✅ Syntax Explanation

number.toLocaleString(locale, options)
  • locale → Defines region formatting ("en-US", "en-IN", "de-DE")
  • options → Formatting configuration (currency, decimal places, etc.)

💵 Example: USD Formatting

let amount = 1234567.89;

let formattedUSD = amount.toLocaleString("en-US", {
  style: "currency",
  currency: "USD"
});

console.log(formattedUSD);
// Output: $1,234,567.89

Example: INR Formatting

let amount = 1234567.89;

let formattedINR = amount.toLocaleString("en-IN", {
  style: "currency",
  currency: "INR"
});

console.log(formattedINR);
// Output: ₹12,34,567.89

Notice the Indian numbering system (lakhs grouping).

Parameters Breakdown

ParameterPurpose
style"currency" for money formatting
currencyISO currency code (USD, INR, EUR)
minimumFractionDigitsMinimum decimal places
maximumFractionDigitsMaximum decimal places

Recommended Method: Using Intl.NumberFormat

Why It’s More Flexible

  • Reusable formatter instance
  • Better performance in loops
  • Cleaner for multi-currency apps
  • More customization options

Syntax & Constructor Explanation

new Intl.NumberFormat(locale, options)

You create a formatter object and reuse it.

💵 Example: Format in USD

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

console.log(usdFormatter.format(1234567.89));
// $1,234,567.89

💶 Example: Format in EUR

let eurFormatter = new Intl.NumberFormat("de-DE", {
  style: "currency",
  currency: "EUR"
});

console.log(eurFormatter.format(1234567.89));
// 1.234.567,89 €

💰 Example: Format in INR

let inrFormatter = new Intl.NumberFormat("en-IN", {
  style: "currency",
  currency: "INR"
});

console.log(inrFormatter.format(1234567.89));
// ₹12,34,567.89

🎯 Customizing Decimal Places

let customFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  minimumFractionDigits: 0,
  maximumFractionDigits: 0
});

console.log(customFormatter.format(1234567.89));
// $1,234,568

✔ Useful when displaying rounded totals.

Formatting Without Currency Symbol (Optional)

Sometimes you only want proper number grouping without the currency sign.

Using style: "decimal"

let numberFormatter = new Intl.NumberFormat("en-US", {
  style: "decimal"
});

console.log(numberFormatter.format(1234567.89));
// 1,234,567.89

📌 When to Use It

  • Analytics dashboards
  • Reports showing numeric values
  • Internal calculations display
  • When currency symbol is added separately

Custom Currency Formatting (Manual Approach)

⚠️ Not recommended unless absolutely required.

Using .toFixed()

let amount = 1234567.89;
let fixed = amount.toFixed(2);

console.log(fixed);
// "1234567.89"

Adding Symbol Manually

let formatted = "$" + fixed;
console.log(formatted);
// $1234567.89

Regex for Thousand Separators

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

console.log(formatted);
// $1,234,567.89

📌 When Custom Formatting Is Required

  • Legacy browsers without Intl support
  • Highly customized financial formats
  • Non-standard grouping rules
  • Embedded systems / limited JS environments

Handling Dynamic Currency Codes

In global SaaS applications, currency changes based on user location.

Passing Currency Dynamically

function formatCurrency(amount, locale, currencyCode) {
  return new Intl.NumberFormat(locale, {
    style: "currency",
    currency: currencyCode
  }).format(amount);
}

console.log(formatCurrency(1000, "en-US", "USD"));
console.log(formatCurrency(1000, "en-IN", "INR"));
console.log(formatCurrency(1000, "de-DE", "EUR"));

🌍 Use Case in Global SaaS Apps

  • Subscription billing systems
  • International e-commerce
  • Multi-country pricing pages
  • Payment gateways
  • Financial reporting tools

✔ Detect user locale
✔ Fetch preferred currency
✔ Pass dynamically to formatter

Currency Formatting in JavaScript

javascript
function formatCurrency(amount, locale = 'en-GB', currency = 'GBP') {
  return new Intl.NumberFormat(locale, { style: 'currency', currency: currency }).format(amount);
}

console.log(formatCurrency(1234567.89)); // £1,234,567.89
console.log(formatCurrency(98765.432, 'en-US', 'USD')); // $98,765.43

  

Explanation of the Code


The code snippet provided is a neat little function that formats numbers into currency strings using JavaScript. Here’s how it works:

  1. The function `formatCurrency` takes up to three arguments: `amount`, `locale`, and `currency`. By default, it uses the British English locale (‘en-GB’) and the British Pound (‘GBP’). But, don’t worry—you’re free to customise it!
  2. It employs the `Intl.NumberFormat` constructor to format the number according to the specified `style` of ‘currency’ and `currency` type. So, the `amount` is formatted as currency based on the `locale` and `currency` you choose.

  3. Calling `formatCurrency(1234567.89)` results in the British Pound formatting: £1,234,567.89.
  4. By adding parameters like in the second example (`formatCurrency(98765.432, ‘en-US’, ‘USD’)`), you get it formatted in the US Dollars: $98,765.43. Pretty handy, right?

Output

£1,234,567.89
$98,765.43

Format numbers as currency strings in JavaScript in Real-World Scenarios


  1. Amazon: Displaying Product Prices
    Amazon needs to display prices consistently across various platforms and currencies. By formatting numbers as currency strings, they ensure the prices are both accurate and easy for customers to understand.
    const price = 29.99;
    const formattedPrice = price.toLocaleString('en-GB', { style: 'currency', currency: 'GBP' });
    console.log(formattedPrice); // Output: £29.99
    This simple method provides clarity, ensuring users see the correct price in the familiar currency format.

  2. Expedia: Calculating Travel Costs
    Expedia uses JavaScript to format travel package costs, helping customers review their expenses in a straightforward manner.
    const travelCost = 1250.50;
    const formattedCost = travelCost.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
    console.log(formattedCost); // Output: $1,250.50
    This ensures that customers can effortlessly compare package prices, facilitating smarter travel decisions.

  3. Etsy: Seller Earnings Visualization
    To give sellers accurate insights into their earnings, Etsy displays earnings in a currency format that sellers can easily interpret.

    const earnings = 455.75;
    const formattedEarnings = earnings.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' });
    console.log(formattedEarnings); // Output: 455,75 €
    This approach provides transparency, promoting trust and satisfaction among their numerous sellers.

Format numbers as currency strings in JavaScript Interview Questions

Formatting numbers as currency in JavaScript can be a bit tricky, and there are plenty of questions folks tend to ask when trying to get this right. Let’s dive into some of the most common and not-so-commonly answered queries, shall we?
  1. How can I format numbers to currency without using locale codes?
    You can manually build a function to prepend a currency symbol and manage comma separation.
    function formatCurrency(number) {
        return '£' + number.toFixed(2).replace(/d(?=(d{3})+.)/g, '$&,');
    }
    console.log(formatCurrency(12345.67)); // "£12,345.67"
    
  2. Is there a lightweight library for currency formatting available?
    Yes, accounting.js is a lightweight library that can help manage currency formatting without the whole shebang of a larger library.
  3. Can I format currency without decimals?
    Certainly! Simply use toFixed(0) in your function.
  4. Is it possible to format currency in scientific notation?
    Not directly, but you can format a number in scientific notation first and then append/prepend the currency sign manually.
  5. How can I display negative numbers as currency with parentheses?
    Customize your function to wrap negative numbers in parentheses along with the currency symbol.
    function formatCurrencyNegative(number) {
        if (number < 0) {
            return '(£' + Math.abs(number).toFixed(2) + ')';
        }
        return '£' + number.toFixed(2);
    }
    
  6. What can I do if the currency symbol should come after the amount?
    Just rearrange the placement within your function.
    function formatCurrencyPostfix(number) {
        return number.toFixed(2) + ' £';
    }
    
  7. How can I format currency for historical exchange rates?
    Use APIs like Open Exchange Rates for fetching historical rates and format accordingly.
  8. Can I localize currency formatting for multiple locales with a fallback?
    Try the Intl.NumberFormat with an options object, and if it fails, use a backup formatting function.
These questions cut to the nitty-gritty of currency formatting, guiding you through practical and creative solutions for coding situations!

Discover our AI-powered js online compiler, where you can instantly write, run, and test your code. Our intelligent compiler simplifies your coding experience, offering real-time suggestions and debugging tips, streamlining your journey from coding novice to expert with ease. Explore it today and boost your coding skills!

Conclusion

'Format numbers as currency strings in JavaScript' enhances your coding toolkit, making your applications more user-friendly and professional. Try mastering this skill to boost your JavaScript capabilities. Visit Newtum to explore further programming languages like Java, Python, C, C++, and more!

Edited and Compiled by

This article was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She's passionate about helping beginners understand technical topics in a more interactive way.

About The Author