Search code examples
javascripthtmldecimallimittofixed

Limit the multiplied amount result to 2 decimals


I made a simple javascript that multiplies an amount and shows the result. However, I want to limit the result to 2 decimals. I've tried using toFixed, but that doesn't seem to work.

Does anyone know how to make this work?


function MultiplyTheAmount() {
	var multiplier = 0.75;
	var roundedMultiplier = multiplier.toFixed(2);
	document.getElementById('multiplyResult').innerHTML = document.getElementById('multiplyAmount').innerHTML * roundedMultiplier;
};
MultiplyTheAmount();
<ul style="list-style:none;">
  <li>Amount:</li>
  <li id="multiplyAmount">119.99</li>
  <li><br/></li>
  <li>Multiply by:</li>
  <li>0.75</li>
  <li><br/></li>
  <li>Result:</li>
  <li id="multiplyResult"></li>
</ul>


Solution

  • Apply the toFixed method to the end result to eliminate the magnified floating point inaccuracy you are seeing:

    function MultiplyTheAmount() {
        var multiplier = 0.75;
        var roundedMultiplier = multiplier.toFixed(2);
        document.getElementById('multiplyResult').textContent = ( 
            +document.getElementById('multiplyAmount').textContent * roundedMultiplier
        ).toFixed(2);
    };
    MultiplyTheAmount();
    <ul style="list-style:none;">
      <li>Amount:</li>
      <li id="multiplyAmount">119.99</li>
      <li><br/></li>
      <li>Multiply by:</li>
      <li>0.75</li>
      <li><br/></li>
      <li>Result:</li>
      <li id="multiplyResult"></li>
    </ul>

    Not related to the question, but I would suggesting the use of textContent instead of innerHTML when not dealing with HTML content.