Ik probeer een shopping cart te maken en daarbij een totaal prijs te calculeren.
Zie mijn fiddle :

Zoals je ziet doet het raar bij het optellen en aftellen en krijg ik nummers zoals 61.010000000000005

Iemand enig idee ?

<?php
//HTML
<body>
<div id="cart">
<h4>Cart ( Total : <span id="total_price">0</span> )</h4>
</div>
<h4>Products</h4>
<div id="products">
<div class="product" id="482734">
<p id="482734_price">10.50</p>
</div>
<div class="product" id="343434">
<p id="343434_price">20.25</p>
</div>
<div class="product" id="978734">
<p id="978734_price">30.26</p>
</div>
</div>
</body>

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready( function(){
$( ".product" ).click(function() {
// Fetch id where the product is in when clicked
var location = $(this).parent().attr("id");
// Fetch product ID
var product = $(this).attr("id");
// Get product price with the product id + _price
var price = parseFloat($("#" + product + "_price").text());
// Get total shopping cart price
var total = parseFloat($('#total_price').text());
// Check where the element is comming from
if (location != 'products') {
// Move product back to products div
$("#" + product).appendTo("#products");
// Decrement total value with product price
total += -1 * price;
// Update total value
$('#total_price').text(total);
} else {
// Move product to shopping cart
$("#" + product).appendTo("#cart");
// Increment total value with product price
total += 1 * price;
// Update total value
$('#total_price').text(total);
}
});
});
</script>
//HTML
?>

$('#total_price').text(Math.round(total*100)/100);


:)
Javascript doet dit vaker. Op (voor mij) onverklaarbare wijze komen er een paar getallen op zoveel posities na de punt te staan.

Oplossing is dus altijd! afronden zoals hierboven door Minouk aangegeven.
Niet alleen Javascript, PHP heeft dat ook.

Iets simpeler:
[code lang="js"]
$('#total_price').text(total.toFixed(2));
[/code]

Reageren