2013-07-17 50 views
0

我正在使用以下jquery腳本來計算我的發票上的實時總計,問題是我似乎無法得到小計到小數點後兩位。jquery輪到2位小數不能按預期工作

如果我添加一行:

subtotal= (subtotal).toFixed(2); 

subtotal += parseFloat(rawValue); 

或試試這個:

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

它只是似乎打破了劇本,我什麼都得不到,然後。我設法獲得了增值稅和總計四捨五入,但由於某種原因,我不能得到小計? :-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> 
+0

用這個? –

+1

您應該逐步調試,並在執行期間查看變量。 –

+1

嘗試先使用'parseFloat',然後'toFixed(2)'。 – Pieter

回答

0

這可能只是值得只是乘以100的數目,則舍入按平時 - 即,使用roundceilfloor,然後通過100希望是有道理分裂。

我在jsfiddle上做了一個簡單的例子,只需點擊'運行'即可。 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; 
} 
0

我到底,這似乎你爲什麼要使用toFixed然後再值解析成float做的工作:)

trimsub = (subtotal - discount).toFixed(2); 
$('#subtotal').text(trimsub); 
$('#subtotalT').val(trimsub);