DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on • Edited on

💰 Currency Formatting in JavaScript

Currency formatting is an essential part of globalizing web applications, and it is crucial to understand the different formatting styles for different countries. Here, we will explore how to format currency using the JavaScript Intl API.

💰 Different Currency Formats in Countries

Different countries have different ways of representing currency values. Here are some examples of different currency formats:

Country Currency Format
United States US Dollar $1,000.00
European Union Euro €1.000,00
Japan Japanese Yen ¥1,000

🛠️ Utility Function to Handle Currency Formatting

To make currency formatting easier, we can create a utility function that takes a value and a locale as arguments and returns the formatted currency string.

function formatCurrency(amount, countryCode) {
  const formatter = new Intl.NumberFormat(countryCode, {
    style: 'currency',
    currency: getCurrencyCode(countryCode),
  });

  return formatter.format(amount);
}

function getCurrencyCode(countryCode) {
  switch (countryCode) {
    case 'US':
      return 'USD';
    case 'GB':
      return 'GBP';
    case 'JP':
      return 'JPY';
    case 'DE':
      return 'EUR';
    default:
      return 'USD';
  }
}
Enter fullscreen mode Exit fullscreen mode

The getCurrencyCode function creates a formatter with the style option set to currency, formats the value 1, and returns the currency code from the resulting formatted string.

💰 Example

Let's see an example of how we can use this utility function in a React component. We'll create a simple form that allows the user to enter a value and select a currency.

import React, { useState } from "react";
import { formatCurrency } from "./utils";

const CurrencyConverter = () => {
  const [value, setValue] = useState("");
  const [formattedValue, setFormattedValue] = useState("");

  const handleValueChange = (e) => {
    const inputValue = e.target.value;
    setValue(inputValue);
    setFormattedValue(formatCurrency(inputValue));
  };

  return (
    <div>
      <label htmlFor="currency-input">Enter a value in your currency:</label>
      <input
        id="currency-input"
        type="number"
        value={value}
        onChange={handleValueChange}
      />
      <p>The value in your currency: {formattedValue}</p>
    </div>
  );
};

export default CurrencyConverter;
Enter fullscreen mode Exit fullscreen mode

🎉 Congratulations, you have now learned how to handle currency formats in JavaScript using the Intl API.

Here is the stackblitz: https://stackblitz.com/edit/react-ts-fhuzpd?file=App.tsx

Top comments (0)