/** * Parses a string containing a representation of currency, and returns a typed number. Can handle * different types of currency represenations. * * USD 12,345.65 -> 12345.65 * (USD 12345.00) -> -12345 * * @param text String containing currency representation * @param currencyCode Optionally define different currency code * @returns Parsed currency with type number */ export function parseCurrency(text: string, currencyCode: string = "USD"): number { // TODO: Add ability to handle null fields/not treat null as 0 - KK 9/12/24 // Base case, if text can be cast as a number then work is done if (!isNaN(+text)) return +text; // Remove parentheses and continue parsing, multiply return by -1 to preserve negative value if (text.charAt(0) === '(') return -1 * parseCurrency(text.substring(1, text.length - 1)); // Remove currency code prefix and continue parsing if (text.split(' ')[0] === currencyCode) return parseCurrency(text.split(' ')[1]); // Remove commas and cast to number return Number(text.split(',').join('')); } /** * @param text * @returns */ export function parseNumberOrCurrency(text: string): number | string { if (!isNaN(+text)) return +text; else if (text.charAt(0) === '(') return -1 * parseCurrency(text.substring(1, text.length - 1)); else if (text.split(' ')[0] === "USD") return parseCurrency(text); else return text; }