2016-11-21 141 views
-1

我想計算的價格不含稅實時這樣的:計算價格不含稅沒有給出確切的價格

價格包括taxe(priceTi)= 550

將TaxRate = 10 %

價格不含稅(priceTe)應該= 500

的問題是,我得到priceTe = 499.99999999999994

$(document).on('keyup', "#priceTi", function() { 

    var priceTe = $('#priceTe'); 
    var taxRate = $('#taxRate'); 
    var priceTi = $('#priceTi'); 

    if (taxRate.val() != "") { 
     value = this.value.replace(/,/g, '.'); 
     var tax = parseFloat((taxRate.val()/100) + 1) ; 

     $('#priceTe').val(parseFloat(value)/tax) ; 

     return false; 
    } 
}); 
+1

歡迎即浮點數的快樂痛苦。你可以使用'toFixed()'來解決這個問題。 –

+0

http://stackoverflow.com/questions/588004/is-floating-point-math-broken – epascarello

回答

1

通過使用.toFixed(2)就可以得到所需的結果。

$(document).on('keyup', "#priceTi", function() { 

    var priceTe = $('#priceTe'); 
    var taxRate = $('#taxRate'); 
    var priceTi = $('#priceTi'); 

    if (taxRate.val() != "") { 
     value = this.value.replace(/,/g, '.'); 
     var tax = parseFloat((taxRate.val()/100) + 1) ; 

     $('#priceTe').val(parseFloat(value)/tax).toFixed(2) ; 

     return false; 
    } 
}); 

您也可以使用round四捨五入到最接近的整數。 0.49將被捨去,.5將四捨五入。 此功能Math.round(int)

+0

我已經嘗試過toFixed(2),但它給了499.99999999999994 – hous

+0

鑑於你的號碼,你應該得到495.00 – Mike

+0

它現在的作品,但toFixed()應該在val();)這樣的 $('#priceTe').val(parseFloat((value)/ tax).toFixed()); – hous