Search code examples
javascriptreactjscurrency

React (JavaScript) currency converting not returning correct price


This project itself is using React. The currency converter is apparently a third party JavaScript converter, and is not in React.

The API endpoint does not include the Canadian price, only the US price. There's logic in the React code is converting the currency to Canadian, but the Canadian price is incorrect - it's lower than it should be (it's higher than the US price, which is never the case). Also, the Canadian price is located beside the US flag, it's not the amount beside the Canadian flag.

Disclaimer - this is not my code. I've taken it over from a dev who isn't here anymore. No documentation.

Live link to a page with incorrect Canadian pricing. You can see that where the Canadian price is, which is beside the American flag icon - but it's way lower than the American price of $34,000. Naturally, the Canadian price should be higher.

I've uploaded the full code to Github, which can be found here.

From the "HelperFunctions.ts" file:

export function formatPrice(price, lang, inclCurTxt?: boolean, currency?: string) {
    let formattedPrice = price;
    const usaRate = .74;

    if (lang === "fr") {
        //FRENCH
        const currencyText = (inclCurTxt ? " CA" : "");
        if (currency != null && currency === "US") {
            //USD
            formattedPrice = accounting.formatMoney((Number(price) * usaRate), "", 0, " ") + " $" + currencyText;
        } else {
            //CAD
            formattedPrice = accounting.formatMoney(price, "", 0, " ") + " $" + currencyText;
        }
    } else {//ENGLISH
        const currencyText = (inclCurTxt ? " CAD" : "");
        if (currency != null && currency === "US") {
            //USD
            formattedPrice = accounting.formatMoney((Number(price) * usaRate), "$", 0) + currencyText;
        } else {
            //CAD
            formattedPrice = accounting.formatMoney(price, "$", 0) + currencyText;
        }
    }
    return formattedPrice;
}

From the "MachineImagesAndInfo.tsx" file:

  //PRICE
  if (
    props.jsonDataProduct.price != null &&
    props.jsonDataProduct.price.text != null
  ) {
    detailsHtml.itemPriceCA = formatPrice(
      props.jsonDataProduct.price.text,
      props.lang
    );
    detailsHtml.itemPriceUS = formatPrice(
      props.jsonDataProduct.price.text,
      props.lang,
      false,
      "US"
    );
  }

How can I have the Canadian price converted properly and show the correct price?


Solution

  • It seems that the original function assumes that the input price is given in CAD, and the rate of CADUSD is hardcoded to 0.74. The function takes the price (assuming it's CAD) and multiplies it by 0.74. With the current logic, you should either update the rate to 1.35 or switch the multiplication to a division.

    Overall, I would recommend refactoring. The function is incredibly verbose for a very simple task.