我的javascript没有正确的货币总值

时间:2013-06-02 22:47:06

标签: javascript

我有一个使用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);
}

2 个答案:

答案 0 :(得分:2)

  

十进制值仅显示为整数

然后不要使用parseInt,而是使用parseFloat

答案 1 :(得分:1)

只是评论:

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

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

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