Javascript:无法获得变量和与加法运算符一起使用

Pad*_*wan 0 javascript

我无法通过使用添加来解决var total.它将与乘法运算符一起使用:var total = subtotal*sales_tax但不能使用+符号加法运算符:var total = subtotal + sales_tax.非常感激任何的帮助.

var calculate_click = function () { 
    var subtotal = parseFloat(document.getElementById("subtotal").value).toFixed(3); 
    var taxRate  = parseFloat(document.getElementById("tax_rate").value).toFixed(3);  

    if (isNaN(subtotal) || isNaN(taxRate)) {    
    } 
        else {                                  
        var sales_tax = (subtotal * taxRate / 100); 
        parseFloat(document.getElementById("sales_tax").value = sales_tax.toFixed(3));  

        var total = subtotal + sales_tax;   
        parseFloat(document.getElementById("total").value = total.toFixed(3));  
    }
}
Run Code Online (Sandbox Code Playgroud)

tec*_*bar 5

toFixed()将数字格式化为字符串.因此,之后的算术运算将无法按预期工作.

注意:

  • +(串联)也是字符串的有效操作,因此它将返回"string1string2"- 对于所有其他算术运算,它会自动将字符串转换为数字并执行操作.如果字符串中的数据无法转换,则返回NaN.
  • "12" + "2" => "122""12" * "2" => 24 (number)"hello" * "3" => NaN