首页 > 解决方案 > toFixed 返回错误的输出

问题描述

function get_tax(rent) {
    var pcharges = parseFloat($('#pcharges').val());
    pcharges = pcharges.toFixed(2);
    rent = parseFloat(rent);
    rent = rent.toFixed(2);

    var tax = parseFloat((rent * 15) / 100);
    tax = tax.toFixed(2);

    $('#tax').val(tax);
    var tot_rent = pcharges + rent + tax;
    // alert(tot_rent);
    $('#tot_rent').val(tot_rent);
    // alert(tax);

}

function get_total(pcharges) {
    pcharges = parseFloat(pcharges);
    old_tot = parseFloat($('#tot_rent').val());
    // alert(pcharges+old_tot);
    $('#tot_rent').val(pcharges + old_tot);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" onchange="get_tax(this.value)" type="text" name="rent">
Tax:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tax" type="text" name="tax">
Phone Charges:<input value="0" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" required id="pcharges"  onchange="get_total(this.value)" type="text" name="pcharges">
Total Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tot_rent" type="text" name="tot_rent">

我想从用户那里获得租金并显示 15% 的税费,用户将手动支付电话费,然后我需要添加租金、税费、电话费。税收来得恰到好处,但总租金来得不恰当

标签: javascriptjquery

解决方案


您正在尝试添加toFixed()连接值的字符串值(返回字符串),使用一元加号(+)转换为浮点数,然后执行加法。

function get_tax(rent) {
    var pcharges = parseFloat($('#pcharges').val());
    pcharges = +pcharges.toFixed(2);
    rent = parseFloat(rent);
    rent = +rent.toFixed(2);

    var tax = parseFloat((rent * 15) / 100);
    tax = +tax.toFixed(2);

    $('#tax').val(tax);
    var tot_rent = pcharges + rent + tax;
    // alert(tot_rent);
    $('#tot_rent').val(tot_rent);
    // alert(tax);

}

function get_total(pcharges) {
    pcharges = parseFloat(pcharges);
    old_tot = parseFloat($('#tot_rent').val());
    // alert(pcharges+old_tot);
    $('#tot_rent').val(pcharges + old_tot);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" onchange="get_tax(this.value)" type="text" name="rent">
Tax:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tax" type="text" name="tax">
Phone Charges:<input value="0" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" required id="pcharges"  onchange="get_total(this.value)" type="text" name="pcharges">
Total Rent:<input required onkeyup="this.value=this.value.replace(/[^0-9.]/g,'');" id="tot_rent" type="text" name="tot_rent">


推荐阅读