0

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>
Macchiato
  • 260
  • 4
  • 7
  • 23

2 Answers2

2

You need to limit the final result to have 2 decimal places:

(document.getElementById('multiplyAmount').innerHTML * roundedMultiplier).toFixed(2);
madox2
  • 49,493
  • 17
  • 99
  • 99
1

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.

Community
  • 1
  • 1
trincot
  • 317,000
  • 35
  • 244
  • 286