0

我有一个使用 javascript 汇总其值的表单,它可以正常工作,直到您输入一个包含美分的货币值,因此 2.99 美元的值将仅显示 2.00。这是我的 jsFiddle http://jsfiddle.net/vegas/JwFCB/

    function multiplyRow(row) {

    var this_qty = row + "_value1"
    var this_price = row + "_value2"
    var this_extend = "extend" + row;
    document.getElementById(this_extend).value = (parseInt(document.getElementById(this_qty).value) * parseInt(document.getElementById(this_price).value)) || 0;
    summate();

}

function rateRow(row) {
    var this_payrate = "payrate" + row;
    var this_hours = "hours" + row;
    var this_subtot = "subtotal" + row;
    document.getElementById(this_subtot).value = (parseInt(document.getElementById(this_payrate).value) * parseInt(document.getElementById(this_hours).value)) || 0;
    getlabor();

}

function summate() {
    var materialcost = 0
    for (var i = 1; i <= 5; i++) {
        var id = "extend" + i;
        var thisVal = parseInt(document.getElementById(id).value, 10) || 0;
        materialcost += thisVal;
    }
    document.getElementById("materialcost").value = materialcost || 0;
    tax();
    grandTotal();
}

function getlabor() {
    var labortotal = 0
    var hourCounter = 0
    for (var i = 1; i <= 5; i++) {
        var id = "subtotal" + i;
        var idHours = "hours" + i;
        var thisVal = parseInt(document.getElementById(id).value, 10) || 0;
        var thisValHours = parseInt(document.getElementById(idHours).value, 10) || 0;
        labortotal += thisVal;
        hourCounter += thisValHours;

    }
    document.getElementById("labortotal").value = labortotal || 0;
    document.getElementById("totalhours").value = hourCounter || 0;
    grandTotal();

}

function tax() {
    var materialcost = document.getElementById('materialcost').value || 0;
    var shipping = document.getElementById('shipping').value || 0;
    var salestax = (Math.round(((materialcost / 100) * 8.1) * 100) / 100) || 0;
    var materialtotal = ((materialcost * 1) + (salestax * 1) + (shipping * 1)) || 0;

    document.getElementById('materialcost').value = materialcost;
    document.getElementById('salestax').value = salestax;
    document.getElementById('shipping').value = shipping;
    document.getElementById('materialtotal').value = materialtotal;
    grandTotal();


}

function grandTotal() {
    var labor = parseInt(document.getElementById("labortotal").value, 10) || 0;
    var material = parseFloat(document.getElementById("materialtotal").value, 10) || 0;
    document.getElementById('grandtotal').value = (labor + material).toFixed(2);
}
4

2 回答 2

2

十进制值将仅显示为整数

然后不要使用parseInt,但是parseFloat

于 2013-06-02T22:48:46.800 回答
1

只是一个评论:

只有在使用重载的“+”运算符时,带有字符串的数学才有问题。在您的计算中,您可以使用:

document.getElementById(this_extend).value = document.getElementById(this_qty).value) * document.getElementById(this_price).value;

parseInt 和 parseFloat 的唯一优点是它们修剪尾随的非数字值。在计算中使用它之前,您应该验证用户输入。

于 2013-06-02T23:07:12.370 回答