2016-11-21 49 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