简单的JavaScript添加问题

Sou*_*aby 8 javascript math

我不太喜欢JS,出于某种原因,当我尝试将两个字段添加到一起时,它会加入它们而不是将总和加在一起..这是我正在尝试使用的代码..

    function calculateTotal() {

        var postageVal = document.getElementById('postage').value; //$68.50
        var subtotalVal = document.getElementById('subtotal').value; //$378.00

        var postage = postageVal.substr(1); //68.50
        var subtotal = subtotalVal.substr(1); //378.00
        var totalVal = postage+subtotal;

        alert(postage);
        alert(subtotal);
        alert(totalVal);

    };
Run Code Online (Sandbox Code Playgroud)

totalVal回应/警告68.50378.00而不是将它们加在一起..有人可以告诉我哪里出错了吗?:(想法是用totalVal更新"总"文本字段,但我还没有那么远!

Ray*_*gus 27

在添加之前,您需要将值转换为浮点值:

var totalVal = parseFloat(postage) + parseFloat(subtotal);
Run Code Online (Sandbox Code Playgroud)

编辑:这是一个包含NaN检查的完整示例:

function calculateTotal() {

    var postageVal = document.getElementById('postage').value; //$68.50
    var subtotalVal = document.getElementById('subtotal').value; //$378.00

    var postage = parseFloat(postageVal.substr(1)); //68.50
    var subtotal = parseFloat(subtotalVal.substr(1)); //378.00
    var postageAsFloat = isNaN(postage) ? 0.0 : postage;
    var subtotalAsFloat = isNaN(subtotal) ? 0.0 : subtotal;
    var totalVal = postageAsFloat + subtotalAsFloat;

    alert(postage);
    alert(subtotal);
    alert(totalVal);

};
Run Code Online (Sandbox Code Playgroud)


kar*_*m79 9

尝试将数字转换为浮点数:

function calculateTotal() {

    var postageVal = document.getElementById('postage').value; //$68.50
    var subtotalVal = document.getElementById('subtotal').value; //$378.00

    var postage = parseFloat(postageVal.substr(1)); //68.50
    var subtotal = parseFloat(subtotalVal.substr(1)); //378.00
    var totalVal = postage+subtotal;

    alert(postage);
    alert(subtotal);
    alert(totalVal);

};
Run Code Online (Sandbox Code Playgroud)