0

I am using the following Jquery script to calculate totals in realtime on my invoices, the problem is I cant seem to get subtotal to round to 2 decimal places.

If I add the line :

 subtotal= (subtotal).toFixed(2);

after

subtotal += parseFloat(rawValue);

or try this :

subtotal += parseFloat(rawValue).toFixed(2);

It just seems to break the script and I get nothing at all then. I have managed to get the VAT and grand total rounded but for some reason I cant get the subtotal ? :-S .

           <script type="text/javascript">
           $(document).ready(function () {
              // Calculate sub total
              $('input').on('keyup', function () {
            var rawValue, subtotal = 0;
    $('span[id^="linetotal"]').each(function(i, elem){
         rawValue = $.trim($(this).text());
         if(rawValue == '') rawValue = 0;
         discount = $('#discount').val();
         subtotal += parseFloat(rawValue);
    });
    $('#subtotal').text(subtotal - discount);
    $('#subtotalT').val(subtotal - discount);

    // Calculate vat amount       
        var vatrate = '<?php echo($vatrate);?>';
        subtotal =  $('#subtotal').text(),
               totalprice = parseFloat(subtotal);
                vatamount = (totalprice / 100 * vatrate).toFixed(2);
            $('#vat').text(vatamount);
            $('#vatT').val(vatamount);

    // Calculate grand total
    vatamounttoadd = parseFloat(vatamount);
    subtotaltoadd = parseFloat(subtotal);
    grandtotal = (subtotaltoadd + vatamounttoadd).toFixed(2);
    $('#grandtotal').text(grandtotal);
    $('#grandtotalT').val(grandtotal);

               });  });
           </script>
Iain Simpson
  • 8,011
  • 13
  • 47
  • 66

2 Answers2

1

It may just be worth just multiplying the number by 100, then rounding as you would normally - i.e. using round, ceil or floor, then dividing by 100. Hope that makes sense.

I made a simple example on jsfiddle, just click 'Run'. http://jsfiddle.net/rHwVz/2/

function round_that(round_number){
    ceil_number = Math.ceil(round_number * 100);
    ceil_number = ceil_number / 100;

    floor_number = Math.floor(round_number * 100);
    floor_number = floor_number / 100;

    rounded_number = Math.round(round_number * 100);
    rounded_number = rounded_number / 100;

    // This messy bit just makes a string to append to the document
    return_var = "<b>Number: " + round_number;
    return_var += "</b><br/>Ceil: " + ceil_number;
    return_var += "<br> Floor: " + floor_number + "<br>Round: " + rounded_number

    return return_var;
}
Djave
  • 8,595
  • 8
  • 70
  • 124
0

I used this in the end, which appears to do the job :)

trimsub = (subtotal - discount).toFixed(2);
$('#subtotal').text(trimsub);
$('#subtotalT').val(trimsub);
Iain Simpson
  • 8,011
  • 13
  • 47
  • 66