ChemPal Documentation - v0.0.13-beta.5
    Preparing search index...

    Function parsePrice

    • Parses a price string into a structured object containing currency information. Handles various price formats and number representations:

      • Different currency symbol positions (prefix/suffix)
      • International number formats (e.g., 1.234,56 or 1,234.56)
      • Various currency symbols (€, $, £, ¥, etc.)

      Parameters

      • price: string

        The price string to parse (e.g., "$1,234.56" or "1.234,56€")

      Returns void | ParsedPrice

      Object with currency code, symbol, and numeric price, or undefined if invalid

      parsePrice('$1,234.56')
      // Returns { currencyCode: 'USD', price: 1234.56, currencySymbol: '$' }

      parsePrice('1.234,56€')
      // Returns { currencyCode: 'EUR', price: 1234.56, currencySymbol: '€' }

      parsePrice('£99.99')
      // Returns { currencyCode: 'GBP', price: 99.99, currencySymbol: '£' }

      parsePrice('invalid') // Returns undefined
      export function parsePrice(price: string): ParsedPrice | void {
      if (typeof price !== "string") return;
      const parsed = priceParser.parseFirst(price);

      if (parsed)
      return {
      currencyCode: parsed.currencyCode.toUpperCase(),
      currencySymbol: parsed.symbol,
      price: parsed.floatValue,
      } satisfies ParsedPrice;

      const currencySymbol = getCurrencySymbol(price);
      if (!currencySymbol) return;

      const currencyCode = getCurrencyCodeFromSymbol(currencySymbol);
      let bareAmount = price.replace(currencySymbol, "").trim();

      // Handle foreign number formats where commas and decimals are swapped
      if (bareAmount.match(/^(\d+\.\d+,\d{1,2}|\d{1,3},\d{1,2}|\d{1,3},\d{1,2})$/))
      bareAmount = bareAmount.replaceAll(".", "xx").replaceAll(",", ".").replaceAll("xx", ",");

      // Remove all commas from the amount to make it castable to a number
      bareAmount = bareAmount.replace(/,/g, "");

      return {
      currencyCode,
      currencySymbol,
      price: parseFloat(bareAmount),
      } satisfies ParsedPrice;
      }