2

I have made a compounding calculator function and I am unable to apply toFixed() to it. What I basically want to do is apply toFixed(2) in order to get just two digits after the decimal. Here comes the code thank you very much in advance.

const compound = function () {
  const value1 = document.getElementById("value1").value;
  const value2 = document.getElementById("value2").value;
  const value3 = document.getElementById("value3").value;
  const compResult = document.querySelector(".result").innerHTML =
    value1 * value2 ** value3;
  return compResult.toFixed(2);
};
const calcButton = document.querySelector(".calculate");
calcButton.addEventListener("click", () => {
  compound();
});
2
  • 2
    Are you expecting the content of .result to be compResult.toFixed(2)? Commented Oct 6, 2022 at 9:02
  • 1
    Correct and it was not working but the solution below by Hao Wu works perfectly. Commented Oct 6, 2022 at 9:09

1 Answer 1

2

You need to get the toFixed(2) value first and then display it on .result. The text of .result only changes when you assign its content explicitly.

const compound = function () {
    const value1 = document.getElementById("value1").value;
    const value2 = document.getElementById("value2").value;
    const value3 = document.getElementById("value3").value;
    const compResult = (value1 * value2 ** value3).toFixed(2); 
    document.querySelector(".result").innerText = compResult;
    return compResult;
};
Sign up to request clarification or add additional context in comments.

2 Comments

no need to return anything since the returned value isn't used anyway :p
Just in case, don't want to modify the output of this function :S

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.