I have a function which sum and print a totale of items in my web page,
the function actually just get the actual totale and sum the value of the new item to it.
The issue is that with a start value of 0 for total and them by adding 2.05 at 4th added item the total returns 6.21 instead of 8.20...
The console log of total and val while adding 0 2.05 / 2.05 2.05 / 4.1 2.05 / 6.16 2.05 / total 8.21
My functions looks like this:
function totale(val) {
let totale = parseFloat($(".totale").text().replace("€", ""));
$(".totale").text(formatEuro(totale + parseFloat(val)));
}
function formatEuro(val) {
return (
parseFloat(val)
.toFixed(2)
.replace(/\B(?=(\d{3})+(?!\d))/g, ".") + "€"
);
}
How could i set and get the correct total?
The function totale is called inside another function addProducts() which is triggered on WebSocket message which take as parameter a JSON object which has the amount to be summed. The json passed is like:
products = {
"type": "prod",
"content": {
"desc": "USB TO SERIAL",
"prezzo": 2.20,
"promo": {
"desc": "PROMO IAN",
"prezzo": 0.15
}
}
};
$('.addProduct').on('click', function() {
addProdotto(products.content)
});
function addProdotto(prodotto) {
console.log(prodotto.prezzo)
totale(
prodotto.promo ? (prodotto.prezzo - prodotto.promo.prezzo) : prodotto.prezzo
);
}
function totale(val) {
let totale = parseFloat($(".totale").text().replace("€", ""));
console.log(totale)
$(".totale").text(formatEuro(parseFloat(totale) + parseFloat(val)));
}
function formatEuro(val) {
return (
parseFloat(val)
.toFixed(2)
.replace(/\B(?=(\d{3})+(?!\d))/g, ".") + "€"
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="addProduct">ADD</button>
<h1 class="totale">€0.00</h1>
Here is an example with a button instead of websocket call
Here is what websocket sends when i receive the total 8.21 messages from all the calls:
{type: "prod", content: {desc: "USB TO SERIAL", prezzo: 2.2, promo: {desc: "PROMO IAN", prezzo: 0.15}}}
{"type": "prod", "content": {"desc": "USB TO SERIAL", "prezzo": 2.20, "promo": { "desc": "PROMO IAN", "prezzo": 0.15 }}}
{"type": "prod", "content": {"desc": "USB TO SERIAL", "prezzo": 2.20, "promo": { "desc": "PROMO IAN", "prezzo": 0.15 }}}
{"type": "prod", "content": {"desc": "USB TO SERIAL", "prezzo": 2.20, "promo": { "desc": "PROMO IAN", "prezzo": 0.15 }}}
EDIT 2:
Added the item twice via WebSocket the JSON is the same as above and here is the console log of TOTAL and VAL
After the first sum it become 2.052...