【问题标题】:React (JavaScript) currency converting not returning correct priceReact(JavaScript)货币转换未返回正确的价格
【发布时间】:2020-08-19 23:19:54
【问题描述】:

这个项目本身正在使用 React。货币转换器显然是第三方 JavaScript 转换器,并且不在 React 中。

API 端点不包括加拿大价格,只包括美国价格。 React 代码中的逻辑是将货币转换为加拿大,但加拿大的价格是不正确的 - 它低于应有的价格(它高于美国的价格,但事实并非如此)。另外,加拿大的价格是在美国国旗旁边,不是加拿大国旗旁边的金额。

免责声明 - 这不是我的代码。我已经从一个不再在这里的开发人员那里接管了它。没有文档。

Live link to a page with incorrect Canadian pricing. 你可以看到加拿大的价格在哪里,在美国国旗图标旁边 - 但它比美国的价格 34,000 美元要低得多。当然,加拿大的价格应该更高。

我已将完整代码上传到 Github,可以在 here 找到。

来自“HelperFunctions.ts”文件:

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;
}

来自“MachineImagesAndInfo.tsx”文件:

  //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"
    );
  }

如何正确转换加拿大价格并显示正确的价格?

【问题讨论】:

    标签: javascript reactjs currency


    【解决方案1】:

    似乎原始函数假设输入价格以加元为单位,加元兑美元的汇率被硬编码为 0.74。该函数将价格(假设它是 CAD)乘以 0.74。使用当前逻辑,您应该将比率更新为 1.35,或者将乘法转换为除法。

    总的来说,我建议重构。对于一个非常简单的任务,该函数非常冗长。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多