{"id":21213021,"url":"https://github.com/dev-ahmadbilal/currency-master","last_synced_at":"2026-02-28T02:44:00.283Z","repository":{"id":256127087,"uuid":"854373162","full_name":"dev-ahmadbilal/currency-master","owner":"dev-ahmadbilal","description":"Currency Master provides tools for managing currency, including operations like addition, subtraction, and division, as well as formatting, number-to-words conversion, and currency conversion. It also supports mapping country codes to their respective currencies.","archived":false,"fork":false,"pushed_at":"2024-12-12T04:29:30.000Z","size":699,"stargazers_count":2,"open_issues_count":5,"forks_count":0,"subscribers_count":1,"default_branch":"develop","last_synced_at":"2025-08-09T04:13:43.011Z","etag":null,"topics":["country-codes","currency","currency-api","currency-codes","currency-converter","currency-converter-api","currency-format","currency-formatter","currency-to-words"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/currency-master","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dev-ahmadbilal.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-09-09T03:50:35.000Z","updated_at":"2024-09-15T03:35:53.000Z","dependencies_parsed_at":"2025-07-23T01:42:15.380Z","dependency_job_id":null,"html_url":"https://github.com/dev-ahmadbilal/currency-master","commit_stats":null,"previous_names":["dev-ahmadbilal/currency-master"],"tags_count":4,"template":false,"template_full_name":"dev-ahmadbilal/npm-pkg-boilerplate","purl":"pkg:github/dev-ahmadbilal/currency-master","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dev-ahmadbilal%2Fcurrency-master","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dev-ahmadbilal%2Fcurrency-master/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dev-ahmadbilal%2Fcurrency-master/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dev-ahmadbilal%2Fcurrency-master/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dev-ahmadbilal","download_url":"https://codeload.github.com/dev-ahmadbilal/currency-master/tar.gz/refs/heads/develop","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dev-ahmadbilal%2Fcurrency-master/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29923426,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-27T19:37:42.220Z","status":"online","status_checked_at":"2026-02-28T02:00:07.010Z","response_time":90,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["country-codes","currency","currency-api","currency-codes","currency-converter","currency-converter-api","currency-format","currency-formatter","currency-to-words"],"created_at":"2024-11-20T21:12:50.098Z","updated_at":"2026-02-28T02:44:00.268Z","avatar_url":"https://github.com/dev-ahmadbilal.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Currency Master\n[![npm package][npm-img]][npm-url]\n[![Build Status][build-img]][build-url]\n[![Downloads][download-img]][npm-url]\n[![Issues][issues-img]][issues-url]\n[![Code Coverage][codecov-img]][codecov-url]\n[![Semantic Release][semantic-release-img]][semantic-release-url]\n\n`Currency Master` is a comprehensive TypeScript library that provides utilities for working with various currency-related tasks, such as formatting currency strings, converting amounts between different currencies, converting numerical values to words, and mapping country codes to their respective currency codes.\n\n## Table of Contents\n\n- [Installation](#installation)\n- [Usage](#usage)\n  - [Currency](#currency-class)\n  - [ToWords](#towords)\n  - [CountryCurrencyCode](#countrycurrencycode)\n  - [CurrencyConversion](#currencyconversion)\n  - [UsefulEnums](#useful-enums)\n- [Contributing](#contributing)\n- [License](#license)\n- [Contact](#contact)\n- [Credits](#credits)\n\n\n## Installation\n\nTo install the package, use npm:\n\n```bash\nnpm install currency-master\n```\n\n## Usage\n\nYou can use any of the four classes provided by Currency Master to perform various currency-related tasks.\n\n### `Currency` Class\n\nThe `Currency` class provides a comprehensive set of utilities for handling currency values with various operations such as addition, subtraction, multiplication, division, formatting, and converting values to words. This class is designed to handle different currency formats and supports customizable settings.\n\n#### Features\n\n- **Arithmetic Operations**: Add, subtract, multiply, and divide currency values.\n- **Formatting**: Convert currency values to formatted strings.\n- **Distribution**: Evenly distribute a currency value into parts.\n- **Conversion to Words**: Convert currency values to their word representation.\n- **Customizable Settings**: Configure symbol, decimal separator, precision, grouping, and more.\n\n#### Constructor\n\n##### `Currency(value: number | string | Currency, options?: Partial\u003cCurrencySettings\u003e)`\n\nInitializes a new instance of the `Currency` class.\n\n- **`value`**: The initial value for the currency. It can be a number, string, or another `Currency` instance.\n- **`options`**: An optional configuration object to customize currency settings.\n\n##### Example\n\n```typescript\nconst currency1 = new Currency(1234.56);\nconst currency2 = new Currency('1234.56');\nconst currency3 = new Currency(new Currency(1234.56));\n```\n\n#### Methods\n\n##### `add(amount: number | string | Currency): Currency`\n\nAdds a specified amount to the currency value.\n\n**Example:**\n\n```typescript\nconst currency = new Currency(10);\nconst result = currency.add(5); // Result is a new Currency instance with value 15\n```\n\n##### `subtract(amount: number | string | Currency): Currency`\n\nSubtracts a specified amount from the currency value.\n\n**Example:**\n\n```typescript\nconst currency = new Currency(10);\nconst result = currency.subtract(5); // Result is a new Currency instance with value 5\n```\n\n##### `multiply(factor: number): Currency`\n\nMultiplies the currency value by a specified factor.\n\n**Example:**\n\n```typescript\nconst currency = new Currency(10);\nconst result = currency.multiply(2); // Result is a new Currency instance with value 20\n```\n\n##### `divide(divisor: number): Currency`\n\nDivides the currency value by a specified divisor.\n\n**Example:**\n\n```typescript\nconst currency = new Currency(10);\nconst result = currency.divide(2); // Result is a new Currency instance with value 5\n```\n\n##### `distribute(parts: number): Currency[]`\n\nDistributes the currency value evenly into an array of `Currency` instances.\n\n**Example:**\n\n```typescript\nconst currency = new Currency(100);\nconst parts = currency.distribute(3); // an array of 3 Currency instances with values [33.34, 33.33, 33.33]\n```\n\n##### `dollars(): number`\n\nReturns the dollar portion of the currency value.\n\n**Example:**\n\n```typescript\nconst currency = new Currency(123.45);\nconst dollars = currency.dollars(); // 123\n```\n\n##### `cents(): number`\n\nReturns the cent portion of the currency value.\n\n**Example:**\n\n```typescript\nconst currency = new Currency(123.45);\nconst cents = currency.cents(); // 45\n```\n\n##### `format(options?: Partial\u003cCurrencySettings\u003e): string`\n\nFormats the currency value as a string according to the specified settings.\n\n**Example:**\n\n```typescript\nconst currency = new Currency(1234.56);\nconst formatted = currency.format(); // '$1,234.56'\n```\n\n##### `toString(): string`\n\nConverts the currency value to a string.\n\n**Example:**\n\n```typescript\nconst currency = new Currency(1234.56);\nconst value = currency.toString(); // '1234.56'\n```\n\n##### `toWords(): string`\n\nConverts the currency value into its word representation.\n\n**Default Behavior:**\n\nBy default, the `toWords` method converts the currency amount to words using US dollars:\n```typescript\nconst currency = new Currency(1234.56);\nconst words = currency.toWords(); // 'one thousand two hundred thirty-four dollars and fifty-six cents'\n```\n\n**Customizing Currency Type:**\n\nYou can customize the currency type and locale in the constructor by passing `toWords` options:\n```typescript\nconst c1 = new Currency('1234.56', {\n  toWords: {\n    locale: LocaleEnum.EnglishUnitedKingdom, // Specify the locale\n  },\n});\nconsole.log(c1.toWords()); // 'One Thousand Two Hundred Thirty Four Pounds And Fifty Six Pence Only'\n```\n\n**Support for Multiple Locales:**\n\nThe `toWords` method supports various locales for diverse languages and regions:\n\n**Urdu (Pakistan):**\n```typescript\nconst c2 = new Currency('1234.56', {\n  toWords: {\n    locale: LocaleEnum.UrduPakistan,\n  },\n});\nconsole.log(c2.toWords()); // 'ایک ہزار دو سو چونتیس روپے اور چھپن پیسے صرف'\n```\n\n**Hindi (India):**\n```typescript\nconst c3 = new Currency('1234.56', {\n  toWords: {\n    locale: LocaleEnum.HindiIndia,\n  },\n});\nconsole.log(c3.toWords()); // 'एक हज़ार दो सौ चौंतीस रुपये और छप्पन पैसे'\n```\n\nThe `toWords` method is highly versatile and supports various locales, enabling you to format numbers into words in different languages and regional formats.\n#### Configuration\n\nThe `Currency` class supports various configuration options through the `CurrencySettings` type:\n\n- **`symbol`**: Currency symbol (default: `$`).\n- **`separator`**: Thousands separator (default: `,`).\n- **`decimal`**: Decimal separator (default: `.`).\n- **`errorOnInvalid`**: Whether to throw an error on invalid input (default: `false`).\n- **`precision`**: Number of decimal places (default: `2`).\n- **`pattern`**: Format pattern for positive values (default: `!#`).\n- **`negativePattern`**: Format pattern for negative values (default: `-!#`).\n- **`fromCents`**: Whether the initial value is in cents (default: `false`).\n- **`groups`**: Regular expression for grouping digits (default: `/(\\d)(?=(\\d{3})+\\b)/g`).\n- **`format`**: Function to format the currency object (default: `formatCurrency`).\n- **`toWords`**: Custom settings for currency to words (optional).\n\n#### Example: Using Custom Currency Settings\n\nIn this example, we'll create a `Currency` instance with custom settings and perform various operations.\n\n#### Custom Settings\n\nLet's define custom settings for the `Currency` class:\n\n```typescript\nconst customSettings: CurrencySettings = {\n  symbol: '€',\n  separator: '.',\n  decimal: ',',\n  precision: 2,\n  pattern: '!# €',\n  negativePattern: '-!# €',\n  fromCents: false,\n  groups: /(\\d)(?=(\\d{3})+(?!\\d))/g,\n};\n```\n\n#### Creating a Currency Instance with Custom Settings\n\nNow we'll create a `Currency` instance using the custom settings and perform some operations:\n\n```typescript\nimport Currency from './currency';\n\n// Create a Currency instance with a value of 1234.56 and custom settings\nconst customCurrency = new Currency(1234.56, customSettings);\n\n// Display the value formatted according to the custom settings\nconsole.log(customCurrency.format()); // '1.234,56 €'\n\n// Perform arithmetic operations\nconst addedCurrency = customCurrency.add(765.44);\nconsole.log(addedCurrency.format()); // '2.000,00 €'\n\nconst subtractedCurrency = customCurrency.subtract(234.56);\nconsole.log(subtractedCurrency.format()); // '1.000,00 €'\n\n// Multiply and divide\nconst multipliedCurrency = customCurrency.multiply(1.5);\nconsole.log(multipliedCurrency.format()); // '1.851,84 €'\n\nconst dividedCurrency = customCurrency.divide(2);\nconsole.log(dividedCurrency.format()); // '617,28 €'\n\n// Distribute the currency into 3 parts\nconst distributedCurrencies = customCurrency.distribute(3);\ndistributedCurrencies.forEach((currency, index) =\u003e {\n  console.log(`Part ${index + 1}: ${currency.format()}`);\n});\n//\n// Part 1: '411,52 €'\n// Part 2: '411,52 €'\n// Part 3: '411,52 €'\n\n// Convert to words\nconsole.log(customCurrency.toWords()); // 'one thousand two hundred thirty-four euros and fifty-six cents'\n```\n\n### ToWords\n\nThe `ToWords` class provides methods to convert numerical values to their word representations.\n\n#### Example\n\n```typescript\nimport { ToWords } from 'currency-master';\n\n// Convert a number to words\nconst words = ToWords.convert(123);\nconsole.log(words); // \"one hundred and twenty-three\"\n\n// Convert a negative number\nconst negativeWords = ToWords.convert(-123);\nconsole.log(negativeWords); // \"minus one hundred and twenty-three\"\n```\nOptions can be set at instance level, or along with individual call to `convert` method.\n\n```ts\nconst toWords = new ToWords();\n\nwords = toWords1.convert(123.045, { currency: false, ignoreDecimal: false });\nconsole.log(words); //  One Hundred Twenty Three Point Zero Four Five\n\nwords = toWords1.convert(123.045, { currency: false, ignoreDecimal: true });\nconsole.log(words); //  One Hundred Twenty Three\n```\n\n#### Config Options\n\nThe `ToWords` class suppose following custom options \n\n- **`locale` (LocaleEnum, default: `LocaleEnum.EnglishUnitedStates`)**:\n  - Sets the locale for internationalization (i18n), determining the language and regional formatting for the words.\n\n- **`currency` (boolean, default: `true`)**:\n  - Indicates if the number should be converted into words formatted as currency.\n  - When set to `true`, the number will be rounded to two decimal places before conversion.\n  - Includes currency symbols and adjusts pluralization of currency units.\n\n- **`ignoreDecimal` (boolean, default: `false`)**:\n  - Determines whether to disregard the fractional (decimal) part of the number during conversion.\n  - When `true`, only the integer part is converted to words, ignoring the decimal portion.\n\n- **`ignoreZeroCurrency` (boolean, default: `false`)**:\n  - Specifies whether to omit zero value in the currency portion of the words.\n  - When `true`, zero currency units will not be included in the output, avoiding redundant mentions.\n\n- **`doNotAddOnly` (boolean, default: `false`)**:\n  - Controls whether to append the word \"only\" at the end of the converted currency words.\n  - Works only when `currency` is `true`. When `true`, \"only\" is not included in the output.\n\n- **`currencyOptions` (object, default: `undefined`)**:\n  - Allows customization of currency options while retaining the language settings from the locale.\n  - Useful for specifying different currencies (e.g., using EUR instead of USD) while converting to words in a specific language.\n  - Supports dynamic currency changes for each conversion call, applicable only when `currency` is `true`.\n\n```ts\nconst toWords = new ToWords({\n  locale: LocaleEnum.EnglisUnitedStates,\n  converterOptions: {\n    currency: true,\n    ignoreDecimal: false,\n    ignoreZeroCurrency: false,\n    doNotAddOnly: false,\n    currencyOptions: {\n      name: 'Dollar',\n      plural: 'Dollars',\n      symbol: '$',\n      fractionalUnit: {\n        name: 'Cent',\n        plural: 'Cents',\n        symbol: '',\n      },\n    },\n  },\n});\n```\n#### Supported Locales\n\n  | Country             | Language   | Locale          |\n  | ------------------- | ---------- | --------------- |\n  | UAE                 | English    | en-AE           |\n  | Bangladesh          | English    | en-BD           |\n  | UK                  | English    | en-GB           |\n  | Ghana               | English    | en-GH           |\n  | Ireland             | English    | en-IE           |\n  | India               | English    | en-IN           |\n  | Myanmar             | English    | en-MM           |\n  | Mauritius           | English    | en-MU           |\n  | Nigeria             | English    | en-NG           |\n  | Nepal               | English    | en-NP           |\n  | USA                 | English    | en-US (default) |\n  | Philippines         | English    | en-PH           |\n  | Estonia             | Estonian   | ee-EE           |\n  | Iran                | Persian    | fa-IR           |\n  | Belgium             | French     | fr-BE           |\n  | France              | French     | fr-FR           |\n  | India               | Gujarati   | gu-IN           |\n  | India               | Hindi      | hi-IN           |\n  | India               | Marathi    | mr-IN           |\n  | Suriname            | Dutch      | nl-SR           |\n  | Brazil              | Portuguese | pt-BR           |\n  | Turkey              | Turkish    | tr-TR           |\n  | Korean, Republic    | Hangul     | ko-KR           |\n  | Pakistan            | English    | en-PK           |\n  | Pakistan            | Urdu       | ur-PK           |\n\n### CountryCurrencyCode\n\nThe `CountryCurrencyCode` class provides utility methods to map country codes to their respective currency codes.\n\n#### Example\n\n```typescript\nimport { CountryCurrencyCode } from 'currency-master';\n\n// Get the currency code by country code\nconst currency = CountryCurrencyCode.getCurrencyByCountryCode('US');\nconsole.log(currency); // 'USD'\n\n// Get all country codes using a specific currency\nconst countries = CountryCurrencyCode.getCountriesByCurrencyCode('USD');\nconsole.log(countries); // ['US', 'UM']\n\n// Get all the country codes\nconst countryCodes = CountryCurrencyCode.getAllCountryCodes();\nconsole.log(countryCodes); // List of all all country codes\n\n// Get all currency codes\nconst currencyCodes = CountryCurrencyCode.getAllCurrencyCodes();\nconsole.log(currencyCodes); // List of all currency codes\n```\n### CurrencyConversion\n\nThe `CurrencyConversion` class provides methods for fetching real-time or historical exchange rates and converting currency from one type to another. It interacts with the [Fawaz Ahmed Currency API](https://github.com/fawazahmed0/currency-api) to retrieve exchange rates.\n\n#### Fetching Currency Rates\n\nYou can fetch the latest exchange rates for a specific currency, or fetch historical rates by specifying a date in the `YYYY-MM-DD` format.\n\n#### Fetching Latest Rates\n\n```ts\nconst rates = await CurrencyConversion.getCurrencyRates(CurrencyEnum.UnitedStatesDollar);\nconsole.log(rates); // Output: { \"eur\": 0.92, \"gbp\": 0.80, ... }\n```\n\n#### Fetching Historical Rates\n\n```ts\nconst historicalRates = await CurrencyConversion.getCurrencyRates(CurrencyEnum.UnitedStatesDollar, '2024-09-01');\nconsole.log(historicalRates); // Output: { \"eur\": 0.90, \"gbp\": 0.78, ... }\n```\n\n#### Converting Currency\n\nYou can convert a specific amount from one currency to another using either real-time or historical exchange rates.\n\n##### Real-Time Conversion\n\n```ts\nconst convertedAmount = await CurrencyConversion.convert(CurrencyEnum.UnitedStatesDollar, CurrencyEnum.Euro, 100);\nconsole.log(convertedAmount); // Output: \"92.00\" (depending on the exchange rate)\n```\n\n##### Historical Conversion\n\n```ts\nconst historicalConversion = await CurrencyConversion.convert(CurrencyEnum.UnitedStatesDollar, CurrencyEnum.Euro, 100, '2024-09-01');\nconsole.log(historicalConversion); // Output: \"90.00\" (depending on the historical rate)\n```\n\n#### API Reference\n\n##### `CurrencyConversion`\n\n- `getCurrencyRates(currency: CurrencyEnum, date?: string): Promise\u003cCurrencyRates\u003e`\n  - **currency**: Base currency (e.g., `CurrencyEnum.USD`).\n  - **date** (optional): Historical date in `YYYY-MM-DD` format. If omitted, the latest rates will be fetched.\n  - **Returns**: A promise that resolves to the exchange rates for the base currency.\n\n- `convert(from: CurrencyEnum, to: CurrencyEnum, amount: number, date?: string): Promise\u003cstring\u003e`\n  - **from**: Base currency.\n  - **to**: Target currency.\n  - **amount**: Amount to convert.\n  - **date** (optional): Historical date for conversion. If omitted, the latest exchange rates will be used.\n  - **Returns**: A promise that resolves to the converted amount (as a string with two decimal places).\n\n### Useful Enums\n\n#### `CurrencyEnum`\n\nIt contains a set of predefined currency codes to be used with the `CurrencyConversion` class.\n\nExample:\n\n```ts\nCurrencyEnum.Euro                 // Euro\nCurrencyEnum.UnitedStatesDollar   // US Dollar\n```\n\n\n#### `CountryCurrencyEnum`\n\nIt contains a mapping of country codes to currency codes.\n\nExample:\n\n```ts\nCountryCurrencyEnum.US   // USD\nCountryCurrencyEnum.AE   // AED\n```\n\n## Contributing\n\nContributions are welcome! Please see the [Contributing Guidelines](CONTRIBUTING.md) for more details.\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more information.\n\n## Contact\n\nIf you have any questions, suggestions, or would like to collaborate, please feel free to reach out:\n\n- **Email:** [ahmadbilal.3491@gmail.com](mailto:ahmadbilal.3491@gmail.com)\n- **LinkedIn:** [Ahmad Bilal](https://www.linkedin.com/in/ahmad-bilal-920637165)\n\nI look forward to hearing from you!\n\n## Credits\n\nI would like to acknowledge the following resources that were instrumental in the development of this package:\n\n- [**currency.js**](https://www.npmjs.com/package/currency.js): This library provided valuable insights and inspiration for handling currency formatting and conversion.\n- [**to-words**](https://www.npmjs.com/package/to-words): A useful package for converting numbers to words, which served as a reference for implementing similar functionality.\n- [**country-to-currency**](https://www.npmjs.com/package/country-to-currency): A helpful resource for mapping countries to their respective currencies.\n- [**exchange-api**](https://github.com/fawazahmed0/exchange-api): An open-source API used for currency exchange rates, which guided the implementation of currency conversion features.\n\nThank you to these projects for their contributions to the open-source community!\n\n[build-img]:https://github.com/dev-ahmadbilal/currency-master/actions/workflows/release.yml/badge.svg\n[build-url]:https://github.com/dev-ahmadbilal/currency-master/actions/workflows/release.yml\n[npm-img]:https://img.shields.io/npm/v/currency-master\n[npm-url]:https://www.npmjs.com/package/currency-master\n[download-img]: https://badgen.net/npm/dt/currency-master\n[issues-img]:https://img.shields.io/github/issues/dev-ahmadbilal/currency-master\n[issues-url]:https://github.com/dev-ahmadbilal/currency-master/issues\n[codecov-img]:https://codecov.io/gh/dev-ahmadbilal/currency-master/branch/main/graph/badge.svg\n[codecov-url]:https://codecov.io/gh/dev-ahmadbilal/currency-master\n[semantic-release-img]:https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg\n[semantic-release-url]:https://github.com/semantic-release/semantic-release\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdev-ahmadbilal%2Fcurrency-master","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdev-ahmadbilal%2Fcurrency-master","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdev-ahmadbilal%2Fcurrency-master/lists"}