Macchiato
Macchiato

Reputation: 260

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>

Upvotes: 0

Views: 120

Answers (2)

trincot
trincot

Reputation: 350270

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.

Upvotes: 1

madox2
madox2

Reputation: 51851

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

(document.getElementById('multiplyAmount').innerHTML * roundedMultiplier).toFixed(2);

Upvotes: 2

Related Questions