0

I have a script that calculates totals based on price, quantity, tax and shipping cost. When I attempt to add them together I receiving high numbers for total cost

Here is the script:

function calculate() {
var total = 0;
var shiptotal = 0;
var subtotal = 0;
var taxtotal = 0;
var taxrate = .078;
$('.button-click').each(function () {
    var amt = parseInt($(this).prev().val());
    var qty = parseInt($(this).parent().find(".quantity").val());
    var ship = parseInt($(this).parent().find(".ik-ship").val());
    shiptotal += (ship * qty);
    subtotal += (amt * qty);
    taxtotal += ( (amt * qty) * taxrate);
    total += ( subtotal + shiptotal + taxtotal );

});
$('#Amount').val(total.toFixed(2));
 $('.total-amount').html( total.toFixed(2) );
 $('.sub-total-amount').html( subtotal.toFixed(2) );
 $('.shipping-amount').html( shiptotal.toFixed(2) );
 $('.tax-amount').html( taxtotal.toFixed(2) );
}

A product that cost $62.00 and has $3.00 in shipping comes out like this:

SUB-TOTAL: 62.00
SHIPPING: 3.00
TAX: 4.84
TOTAL: 1257.05 <-- incorrect total -->

I may have been in front of the computer for too long but how do I solve this problem? Please provide an example.

L84
  • 45,514
  • 58
  • 177
  • 257
  • possible duplicate of [Is JavaScript's Floating-Point Math Broken?](http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken) – Daniel A. White Nov 17 '13 at 22:44
  • @DanielA.White - Not sure I follow that question. Also unsure of how the answers can help me fix my problem. – L84 Nov 17 '13 at 22:47
  • Because of precision problems with floating point numbers, you should not use them for monetary calculations. Store and process your prices in cents instead. – Felix Kling Nov 17 '13 at 22:55
  • @FelixKling - Then how would I correct my code to solve the problem? – L84 Nov 17 '13 at 22:56
  • In your case you cannot even use cents since it seems the tax rate is a decimal with three digits after the comma, not two. As Tei already said, you have to work with integers and then divide by 1000. So `taxrate` becomes `78`, `var amt = parseInt((this).prev().val()) * 1000;`, etc. Then you do your multiplications and additions and divide by 1000 at the end. – Felix Kling Nov 17 '13 at 22:59

1 Answers1

0

Use integer math by multiplying the numbers for 1000.

Tei
  • 1,400
  • 8
  • 6