Number to Currency String

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to format a number into a currency string using the Intl.NumberFormat method. This method allows us to format numbers into a currency that is sensitive to country and language formats. We will explore how to use this method with different currencies and language formats to display currency strings in various formats.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28516{{"`Number to Currency String`"}} javascript/data_types -.-> lab-28516{{"`Number to Currency String`"}} javascript/arith_ops -.-> lab-28516{{"`Number to Currency String`"}} javascript/comp_ops -.-> lab-28516{{"`Number to Currency String`"}} end

Number to Currency String

To format a given number as a currency string, use the toCurrency function. This function takes in a number and the currency code as arguments and returns the formatted string.

The function uses Intl.NumberFormat to enable country/currency-specific formatting. You can also optionally pass in a language format to be used for the currency formatting.

const toCurrency = (number, currencyCode, languageFormat) =>
  Intl.NumberFormat(languageFormat, {
    style: "currency",
    currency: currencyCode
  }).format(number);

Here are some examples:

toCurrency(123456.789, "EUR");
// €123,456.79  | currency: Euro | currencyLangFormat: Local

toCurrency(123456.789, "USD", "en-us");
// $123,456.79  | currency: US Dollar | currencyLangFormat: English (United States)

toCurrency(123456.789, "USD", "fa");
// ۱۲۳٬۴۵۶٫۷۹ ؜$ | currency: US Dollar | currencyLangFormat: Farsi

toCurrency(322342436423.2435, "JPY");
// ¥322,342,436,423 | currency: Japanese Yen | currencyLangFormat: Local

toCurrency(322342436423.2435, "JPY", "fi");
// 322 342 436 423 ¥ | currency: Japanese Yen | currencyLangFormat: Finnish

Summary

Congratulations! You have completed the Number to Currency String lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like