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"])
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"])
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
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
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.
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"])
Displaying amounts
Finally displaying amounts involves adding currency symbols to the amount formatted. Use the following functions
The first function getDisplayAmountOnCurrency takes currency details -
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"])
The second function, getDisplayAmountOnCurrencyCode only takes a currencySymbol, but its a promise.
const roundedAmount = getRoundedAmount(123.4517, 2); // 123.46 const roundedAmount = getRoundedAmount(123.4517, 2, true); // 123.45
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.
The above is the detailed content of Managing countries and currencies with JS. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
