以十进制显示总共2个数字

时间:2014-08-01 05:12:29

标签: javascript html

我试图显示2总数的2小数点并减去它们但它没有计算小数点。任何人都想弄清楚这一点。感谢。

function calculate() {

    var myBox1 = document.getElementById('box1').value;
    var myBox2 = document.getElementById('box2').value;
    var basicpay = document.getElementById('basicpay');
    var myResult = myBox1 * myBox2;
    basicpay.value = myResult.toFixed(2);

    document.getElementById('both').value = sum() - diff();
}

这是差异部分

function diff() {

    var absent = document.getElementById('absent').value;
    var tardiness = document.getElementById('tardiness').value;
    var sss = document.getElementById('sss').value;
    var pagibig = document.getElementById('pagibig').value;
    var philhealth = document.getElementById('philhealth').value;
    var cashadvances = document.getElementById('cashadvances').value;
    var withholdingtax = document.getElementById('withholdingtax').value;
    var others = document.getElementById('others').value;

    var result =

        parseInt(absent) +
        parseInt(tardiness) +
        parseInt(sss) +
        parseInt(pagibig) +
        parseInt(philhealth) +
        parseInt(cashadvances) +
        parseInt(withholdingtax) +
        parseInt(others) || 0;


    if (!isNaN(result)) {
        document.getElementById('totaldeductions').value = result.toFixed(2);
        return result;
    }
}

这是总和部分

function sum() {
    var basicpay = document.getElementById('basicpay').value;
    var overtime = document.getElementById('overtime').value;
    var regularholiday = document.getElementById('regularholiday').value;
    var specialholiday = document.getElementById('specialholiday').value;
    var allowanceday = document.getElementById('allowanceday').value;
    var monthpay = document.getElementById('monthpay').value;
    var others1 = document.getElementById('others1').value;

    var result =

        parseInt(basicpay) +
        parseInt(overtime) +
        parseInt(regularholiday) +
        parseInt(specialholiday) +
        parseInt(allowanceday) +
        parseInt(monthpay) +
        parseInt(others1) || 0;

    if (!isNaN(result)) {
        document.getElementById('totalgrosspay').value = result.toFixed(2);
        return result;
    }
}

1 个答案:

答案 0 :(得分:1)

在Sum()和Diff()函数中,您只使用整数。整数只是整数,因此在小数点后不会保留任何内容。要处理小数,您需要使用JavaScript的parseFloat()函数。举一个例子,在Sum()函数中,您可以将结果计算更改为如下所示:

var result = 

    parseFloat(basicpay) + 
    parseFloat(overtime) +
    parseFloat(regularholiday) +
    parseFloat(specialholiday) +
    parseFloat(allowanceday) +
    parseFloat(monthpay) +
    parseFloat(others1) || 0;

这将保留数字中的小数点而不是截断为整数作为parseInt()

相关问题