简体   繁体   中英

Javascript: Can't get variable sum to work with addition operator

I can't get the var total to resolve by using addition. It will work with multiplication operator: var total = subtotal * sales_tax but not with the + sign addition operator: var total = subtotal + sales_tax. Any help would be most appreciated.

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));  
    }
}

toFixed() formats the number into a string . So arithmetic operations afterwards will not work as expected.

Note:

  • + (concatenation) is a valid operation for strings as well, so it'll return "string1string2" - For all other arithmetic operations it auto converts the strings to numbers and performs the operation. If the data within the strings cannot be converted, it returns NaN .
  • "12" + "2" => "122" whereas "12" * "2" => 24 (number) and "hello" * "3" => NaN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM