diff --git a/src/index.d.ts b/src/index.d.ts index ad6d31e..d9f1f73 100644 --- a/src/index.d.ts +++ b/src/index.d.ts @@ -17,3 +17,10 @@ export function formatCurrency( locale: string, raw: boolean ): string; + +// format currency with names +export function formatCurrencyWithNames( + amount: number, + isoCode: string, + locale: string +): string; diff --git a/src/index.js b/src/index.js index 9afe0fd..20d071a 100644 --- a/src/index.js +++ b/src/index.js @@ -319,3 +319,37 @@ export function formatCurrency(amount, isoCode, locale = "en", raw = false) { } } } + +export function formatCurrencyWithNames(amount, isoCode, locale = "en") { + isoCode = isoCode.toUpperCase(); + if (currentISOCode !== isoCode || currentLocale != locale) { + currentISOCode = isoCode; + currentLocale = locale; + + // Formatters are tied to currency code, we try to initialize as infrequently as possible. + initializeFormatters(isoCode, locale); + } + + const absPrice = Math.abs(Number(amount)); + let price = 0; + let suffix = ""; + if (absPrice >= 1.0e9) { + // If Billion + price = absPrice / 1.0e9; + suffix = "B"; + } else if (abs >= 1.0e6) { + // If Million + price = absPrice / 1.0e6; + suffix = "M"; + } else if (absPrice >= 1.0e3) { + // If Thousands + price = absPrice / 1.0e3; + suffix = "K"; + } + if (isCrypto(isoCode)) { + price = Number(price.toFixed(3)); + return `${price}${suffix} ${isoCode}`; + } else { + return formatCurrency(price, isoCode, locale, false) + suffix; + } +} diff --git a/src/test.js b/src/test.js index 19bad55..7ffa864 100644 --- a/src/test.js +++ b/src/test.js @@ -1,4 +1,9 @@ -import { formatCurrency, isCrypto, clearCache } from "./index"; +import { + formatCurrency, + isCrypto, + clearCache, + formatCurrencyWithNames +} from "./index"; test("isCrypto", () => { expect(isCrypto("BTC")).toBe(true); @@ -148,3 +153,24 @@ describe("Intl.NumberFormat not supported", () => { }); }); }); + +describe("large number", () => { + describe("Billion", () => { + const billionVal1 = 9.101222e9; + const billionResVal1 = "9.101B"; + const billionVal2 = 9e9; + const billionResVal2 = "9B"; + + test("format USD", () => { + expect(formatCurrencyWithNames(billionVal1, "USD", "en")).toEqual( + "USD " + billionResVal1 + ); + }); + + test("format BTC", () => { + expect(formatCurrencyWithNames(billionVal2, "BTC", "en")).toEqual( + billionResVal2 + " BTC" + ); + }); + }); +});