Reputation: 728
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));
}
}
Upvotes: 0
Views: 738
Reputation: 66693
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
Upvotes: 5