DEV Community

Cover image for Managing countries and currencies with JS

Managing countries and currencies with JS

Managing list of countries and currencies along with formatting different currency formats for all the different countries can present some challenges and work in our projects. Firstly, we do not want to carry around list of 200 countries and their currencies, dial codes, flag emojies in our codebase, specially on the front end. Secondly, every country follows different currency symbols, different formatting, like comma placements and different decimal precisions needs to be managed.

This is why the npm package country-currency-utils was written. Its written in typescript, suitable in any project that uses javascript, whether on the server or frontend.

Countries

We have a list of countries hosted through CDN which can be accessed through the COUNTRIES_DETAILS_URL variable from the package. The response is a key value object where key is the 2-letter ISO standard country code. The value object contains Dial code, Currency code (ISO standard) and flag emojis. The following functions can be used to list out countries from the package.

type TCountryDetails = {
  name: string; // Country name
  dialCode: string; // Country dial code
  currencyCode: string; // Country currency code
  flagEmoji: string; // Country flag emoji
};

type TCountryData = TCountryDetails & {
  countryCode: string; // ISO 3166 country code
};

getAllCountryDetails(): Promise<Record<string, TCountryDetails>>
getAllCountryData(): Promise<TCountryData[]>
getCountryData(countryCode: string): Promise<TCountryData | undefined>
getCountryData(countryCode: string): Promise<TCountryData | undefined>

// examples

const allCountriesData = await getAllCountryData()
const countryData = await getCountryData("US")
const countriesData = await getCountriesData(["US", "BD"])
Enter fullscreen mode Exit fullscreen mode

Currencies

We also have a list of currencies hosted through CDN accessible with the CURRENCIES_DETAILS_URL variable. It contains a key value object where key is ISO standard currency code and the value is an object with different currency details like currency symbols (native and standard), digit grouping (million-billion or Lakh-Crore), and decimal precision followed with the currency. Here are functions to use the data.

type TCurrencyDetails = {
  name: string; // Currency name
  demonym: string; // Currency demonym
  majorSingle: string; // Major unit name in singular form (e.g. Dollar)
  majorPlural: string; // Major unit name in plural form (e.g. Dollars)
  symbol: string; // Currency symbol (e.g. $, CA$)
  symbolNative: string; // Currency symbol in native language (e.g. $)
  symbolPreferred: string; // preferred currency symbol, used for display
  minorSingle: string; // Minor unit name in singular form (e.g. Cent)
  minorPlural: string; // Minor unit name in plural form (e.g. Cents)
  decimals: number; // Number of decimal places, used for standard display
  decimalsCompact: number; // Number of decimal places, used for compact display
  digitGrouping: 2 | 3; // Digit grouping for formatting (e.g. 2 for 1,00,000, 3 for 100,000)
};

type TCurrencyData = TCurrencyDetails & {
  currencyCode: string; // ISO 4217 currency codes
};

getAllCurrencyDetails(): Promise<Record<string, TCurrencyDetails>>
getAllCurrencyData(): Promise<TCurrencyData[]>
getCurrencyData(currencyCode: string): Promise<TCurrencyData | undefined>
getCurrenciesData(currencyCodes: string[]): Promise<(TCurrencyData | undefined)[]>

// Examples

const allCurrenciesData = await getAllCurrencyData()
const currencyData = await getCurrencyData("USD")
const currenciesData = await getCurrenciesData(["USD", "BDT"])
Enter fullscreen mode Exit fullscreen mode

Amount Formatting Utilities

When developing a project that handles multiple currencies can be a challenge for a number of reasons -

  • Handle decimal place accuracies of the currencies
  • Show proper symbols (native and standard symbols)
  • Format the currencies with comma separation

The currency list of data contains all of the important data needed for proper display of monetary amounts. There are also utility functions that help with handling monetary amounts.

Rounding amounts

The default to round monetary amount is to ceil the amount. However you can also round the amount in the middle.

const roundedAmount = getRoundedAmount(123.4517, 2); // 123.46
const roundedAmount = getRoundedAmount(123.4517, 2, true); // 123.45
Enter fullscreen mode Exit fullscreen mode

You may also want to round amounts depending on the currency. Here, we have another function to round on the currency details.

const USDCurrencyData = await getCurrencyData("USD");
const BDTCurrencyData = await getCurrencyData("BDT");

const roundedAmount = getRoundedAmountOnCurrency(123.4567, USDCurrencyData); // 123.46
const roundedAmount = getRoundedAmountOnCurrency(123.45, BDTCurrencyData); // 124
const roundedAmount = getRoundedAmountOnCurrency(123.45, BDTCurrencyData, {
  isDecimalsStandard: true,
}); // 123.45
Enter fullscreen mode Exit fullscreen mode

Note: You will notice that we use a promise to read the CurrencyDetails first. It is important to handle this way as we do not want to carry a list of all currency details in our codebase. So we fetch the data and use it. But you can also decide to keep a copy and use the getRoundedAmountOnCurrency function. The same idea applies for the next functions.

Formatting amounts

Formatting amounts returns strings for display purposes. Formatting amounts involves two things

  • Give the amount fixed decimal places
  • Return a comma separated amount

Use the following function to format amounts on currency.

// reference
type TCurrencyFormatOptions = TCurrencyRoundOptions & {
  avoidRound?: boolean; // avoids rounding amount
  avoidFixedDecimals?: boolean; // default behavior is to have fixed decimals
};

getFormattedAmountOnCurrency(amount: number, currencyData?: TCurrencyData, options?: TCurrencyFormatOptions): string

// example
const USDCurrencyData = await getCurrencyData("USD");
const BDTCurrencyData = await getCurrencyData("BDT");

const formattedAmount = getFormattedAmountOnCurrency(123456.7, USDCurrencyData); // "123,456.70"
const formattedAmount = getFormattedAmountOnCurrency(
  123456.7,
  USDCurrencyData,
  {
    avoidFixedDecimals: true,
  }
); // "123,456.7"
const formattedAmount = getFormattedAmountOnCurrency(123456.7, BDTCurrencyData); // "1,23,457"
const formattedAmount = getFormattedAmountOnCurrency(
  123456.7,
  BDTCurrencyData,
  {
    avoidRound: true,
  }
); // "1,23,456.7"
Enter fullscreen mode Exit fullscreen mode

Displaying amounts

Finally displaying amounts involves adding currency symbols to the amount formatted. Use the following functions

The first function getDisplayAmountOnCurrency takes currency details -

// reference
type TCurrencyDisplayOptions = TCurrencyFormatOptions & {
  avoidFormat?: boolean; // Default: format amount
  isSymbolStandard?: boolean; // Default: preferredSymbol, isSymbolStandard: standard symbol
  isSymbolNative?: boolean; // Default: preferredSymbol, isSymbolNative: symbolNative
  separator?: string; // Default: space between symbol and amount, can be changed
};

getDisplayAmountOnCurrency(amount: number, currencyData?: TCurrencyData, options?: TCurrencyFormatOptions): string

// example
const USDCurrencyData = await getCurrencyData("USD");
const BDTCurrencyData = await getCurrencyData("BDT");

const displayAmount = getDisplayAmountOnCurrency(123.4567, USDCurrencyData); // "$ 123.46"
const displayAmount = getDisplayAmountOnCurrency(123456.7, USDCurrencyData); // "$ 123,456.70"
const displayAmount = getDisplayAmountOnCurrency(123.4567, BDTCurrencyData, {
  isSymbolStandard: true,
}); // "৳ 124"
Enter fullscreen mode Exit fullscreen mode

The second function, getDisplayAmountOnCurrencyCode only takes a currencySymbol, but its a promise.

const displayAmount = await getDisplayAmountOnCurrencyCode(123.4567, "USD"); // "$ 123.46"
const displayAmount = await getDisplayAmountOnCurrencyCode(123456.7, "USD"); // "$ 123,456.70"
const displayAmount = await getDisplayAmountOnCurrencyCode(123456.7, "USD", {
  avoidFormat: true,
}); // "$ 123456.7"
const displayAmount = await getDisplayAmountOnCurrencyCode(123456.7, "USD", {
  separator: "",
}); // "$123,456.70"
const displayAmount = await getDisplayAmountOnCurrencyCode(123.4567, "BDT"); // "Tk 124"
const displayAmount = await getDisplayAmountOnCurrencyCode(123.4567, "BDT", {
  isSymbolStandard: true,
}); // "৳ 124"
Enter fullscreen mode Exit fullscreen mode

Conclusion

Many applications deal with countries and currencies and this package was developed to solve a lot of the problems we faced during our work at Headless Technologies Limited and when developing the SAAS sales tech platform engaze.ai used across 30 plus countries.

If you find the package useful, consider starring the package Github Repo.

Feel free to leave a question on the post.

Top comments (0)