Home > Enterprise >  Rate showing Not a Number (NaN)
Rate showing Not a Number (NaN)

Time:01-08

I am trying to build money conversion calculator but the result showing NaN. Can anyone help me with it.

Tried a lot but could not solve it.

enter image description here

Here's the js code

const dropList = document.querySelectorAll("form select"),
  fromCurrency = document.querySelector(".from select"),
  toCurrency = document.querySelector(".to select"),
  getButton = document.querySelector("form button");

for (let i = 0; i < dropList.length; i  ) {
  for (let currency_code in country_list) {
    let selected =
      i == 0
        ? currency_code == "USD"
          ? "selected"
          : ""
        : currency_code == "NPR"
        ? "selected"
        : "";
    let optionTag = `<option value="${currency_code}" ${selected}>${currency_code}</option>`;
    dropList[i].insertAdjacentHTML("beforeend", optionTag);
  }
  dropList[i].addEventListener("change", (e) => {
    loadFlag(e.target);
  });
}

function loadFlag(element) {
  for (let code in country_list) {
    if (code == element.value) {
      let imgTag = element.parentElement.querySelector("img");
      imgTag.src = `https://flagcdn.com/48x36/${country_list[
        code
      ].toLowerCase()}.png`;
    }
  }
}

window.addEventListener("load", () => {
  getExchangeRate();
});

getButton.addEventListener("click", (e) => {
  e.preventDefault();
  getExchangeRate();
});

const exchangeIcon = document.querySelector("form .icon");
exchangeIcon.addEventListener("click", () => {
  let tempCode = fromCurrency.value;
  fromCurrency.value = toCurrency.value;
  toCurrency.value = tempCode;
  loadFlag(fromCurrency);
  loadFlag(toCurrency);
  getExchangeRate();
});

function getExchangeRate() {
  const amount = document.querySelector("form input");
  const exchangeRateTxt = document.querySelector("form .exchange-rate");
  let amountVal = amount.value;
  amountVal = parseFloat(amountVal);
  if (amountVal == "" || amountVal == "0") {
    amount.value = "1";
    amountVal = 1;
  }
  exchangeRateTxt.innerText = "Getting exchange rate...";
  let url = `https://api.fastforex.io/convert?from=${fromCurrency.value}&to=${toCurrency.value}&amount=${amountVal}&api_key=xxx-xxx-xxx`; // api key on p
  fetch(url)
    .then((response) => response.json())
    .then((result) => {
      let exchangeRate = result.rate;
      let totalExRate = (amountVal * exchangeRate).toFixed(2);
      exchangeRateTxt.innerText = `${amountVal} ${fromCurrency.value} = ${totalExRate} ${toCurrency.value}`;
    })
    .catch(() => {
      exchangeRateTxt.innerText = "Something went wrong";
    });
}

Here's the response data

{
  "base": "USD",
  "amount": 1,
  "result": {
    "AED": 3.67,
    "rate": 3.67189
  },
  "ms": 5
}

CodePudding user response:

This part of your code seems to be the issue:

let amountVal = amount.value;
amountVal = parseFloat(amountVal);
if (amountVal == "" || amountVal == "0") {
  amount.value = "1";
  amountVal = 1;
}

where parseFloat() evaluates as NaN right away when the value is empty.

Replace that with:

let amountVal = parseFloat(amount.value ?? "1");
amount.value = amount.value ?? "1"

The ?? operator is useful to set a default value on nullish or undefined.

CodePudding user response:

The result in your .then((result) => method is the response data, and there is no rate value but has result.rate

var result = {
  "base": "USD",
  "amount": 1,
  "result": {
    "AED": 3.67,
    "rate": 3.67189
  },
  "ms": 5
};


console.log( result.rate        ); // undefined
console.log( result.result.rate ); // 3.67189

// assuming that amountVal is 1
let amountVal    = 1;
let exchangeRate = result.result.rate;
let totalExRate  = (amountVal * exchangeRate).toFixed(2);

console.log( totalExRate ); // 3.67

  • Related