Working with Numbers and Currencies in JavaScript using Intl Library

JavaScript
βŒ› 3 minutes read

Introduction

Hello developers! Welcome to a new informative post where we discuss another interesting feature of JavaScript: the Intl library. If you’re aiming to make your applications more user-friendly on an international level, this post will be your roadmap to understanding number parsing and currency conversion using the Intl library.

Introduction to Intl and Number Parsing

When building a global app that serves users worldwide. You’d likely be dealing with different number formats, date-time structures, and currencies. Enter JavaScript’s built-in object, Intl – a handy tool designed for internationalization.

In this article, we’ll focus on the Intl.NumberFormat function. It’s your go-to function for language-sensitive number formatting.

Customizing Number Formatting

Now, let’s unravel the power of Intl.NumberFormat through its options. When passed an options object, this function becomes even more versatile, allowing you to customize your number formatting.

The style could be decimal for plain number formatting, currency for currency formatting, or percent for percent formatting. The default is decimal. Let’s try formatting a number as a currency:

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

console.log(formatter.format(123456.789)); // $123,456.79

The currency field allows you to set the ISO 4217 currency codes, such as USD for the US dollar or EU for the Euro. On the other hand, currencyDisplay decides how to display the currency. You could set it to symbol to use a localized currency symbol, code to use the ISO currency code, or name to use a localized currency name like dollar.

Let’s consider several more scenarios and code examples:

Displaying a number as a percentage

You can use the Intl.NumberFormat object to represent numbers as percentages. This can be especially handy when you’re dealing with statistics or ratios in your app:

let percentFormatter = new Intl.NumberFormat('en-US', { style: 'percent' });
console.log(percentFormatter.format(0.456));
// Expected output: "45%"

In this example, the input number is treated as a decimal, and the formatter converts it to a percentage.

Using different locales

The power of Intl.NumberFormat shines when you’re dealing with international audiences. Let’s format a number using German locale (de-DE):

let formatter = new Intl.NumberFormat('de-DE');
console.log(formatter.format(123456.789));
// Expected output: "123.456,789"

Notice how the thousands separator and decimal point are different from the en-US locale.

Displaying a currency using its ISO code

Instead of showing the currency symbol, you can opt to display the currency’s ISO code. This can be useful when you want to avoid any potential confusion between currencies that share the same symbol:

let formatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', currencyDisplay: 'code' });

console.log(formatter.format(123456.789));
// Expected output: "USD 123,456.79"

Controlling the use of fraction digits

Intl.NumberFormat allows you to specify the minimum and maximum number of fraction digits. This gives you more control over how numbers are displayed:

let formatter = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 4 });
console.log(formatter.format(123456.7891));
// Expected output: "123,456.7891"

let formatter2 = new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
console.log(formatter2.format(123456.7891));
// Expected output: "123,456.79"

In the above examples, the first formatter allows up to four fraction digits, while the second one rounds the number to two fraction digits.

Currency Conversion: Intl.NumberFormat & Live Data

At this point, you might be thinking about converting amounts from one currency to another. While Intl.NumberFormat is a master of formatting, it relies on static information and does not provide live currency rates.Β 

But in this section, we will use a popular free API (ExchangeRate-API) for fetching live currency rates. We will fetch the latest exchange rate from USD to EUR, and use Intl.NumberFormat to format the converted amount.

Please note, to use ExchangeRate-API, you’ll need to sign up for a free API key. Replace YOUR_API_KEY with your actual key in the following example.

// Required for node.js, not needed in the browser
const fetch = require('node-fetch'); 

let amountInUSD = 123456.789;

// API endpoint for fetching USD to EUR rate
let apiUrl = 'https://v6.exchangerate-api.com/v6/YOUR_API_KEY/latest/USD';

fetch(apiUrl)
  .then(response => response.json())
  .then(data => {
    let rate = data.conversion_rates.EUR;
    let amountInEUR = amountInUSD * rate;
    let formatter = new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' });
    console.log(formatter.format(amountInEUR));
  })
  .catch(error => console.log(error));

This script starts by declaring the amount we want to convert in USD. It then sends a request to the API endpoint that provides the latest exchange rates for USD. After receiving the response, it parses it to JSON and extracts the conversion rate for EUR.

The amount in USD is then converted to EUR by multiplying it with the conversion rate. Finally, Intl.NumberFormat is used to format this amount according to German locale conventions for the Euro currency.

Please note that the code uses Promises, which is a modern way to handle asynchronous operations in JavaScript. Also, remember that this code uses the fetch function, which is built-in in modern browsers, but needs to be imported in a Node.js environment.

Further Reading

Conclusion

The world of JavaScript is vast and fascinating. Today, we took a closer look at the Intl library, particularly focusing on number parsing and currency conversion using Intl.NumberFormat. This function, when combined with live data from a currency conversion API, can prove to be an indispensable tool in creating globally appealing applications. Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *