please help me, in JavaScript how can I add multiple numbers as like in an ecommerce shopping cart and display the numbers after the decimal point properly? If the attribute value data-price is 2.50, I would like to display the value as 2.50 on the balance.innerHTML, not as 2.5 as it appears. Here is my code:
<div class="row">
<div class="col6">
2,50$
<div onclick="addC(this)" data-price="2.50">
Add to cart
</div>
</div>
<div class="col6">
2,40$
<div onclick="addC(this)" data-price="2.40">
Add to cart
</div>
</div>
</div>
<div id="balance" data-price="0">0</div>
function addC(product){
let balance = document.getElementById('balance');
balance.innerHTML = parseFloat(Number(balance.innerHTML).toFixed(2)) + parseFloat(Number(product.getAttribute('data-price')).toFixed(3));
}
In this method, can you please tell me, since I am using numbers with decimal points, how can I show them with the zeros, two digits after the decimal point. I want to display them as 2,50 and 2,40 and sum them, but the current output is 2.5 and 2.4 on the DOM:
Use toFixed
on the final sum rather than on the addends.
(2.4 + 2.5).toFixed(2) --> yields "3.30"