简体   繁体   English

JavaScript价格计算错误

[英]Javascript Price Calculation Errors

Discount Calulation do not output. 折扣计算不输出。

(discount is supposed to subtract from Grand Total) (应该从总计中减去折扣)

Html HTML

input name="discount" id="discount" type="text">   <button  id="record_button" onclick="recordToFilename();" href="javascript:void(0);" title="Record" > Submit Discount </button>  
     <b id="discount">Discount</b>

Javascript Java脚本

 function recordTodiscount() {
var input = document.getElementById('discount'),
    discount = input.value;     

check the the jsfiddle click here 检查jsfiddle单击此处

document.getElementById('total').innerHTML = "<strong>SubTotal</strong>: $" + salesTotal.toFixed(2); 
document.getElementById('taxtotal').innerHTML = "<strong>Tax </strong>: $" + salesTotal*0.13.toFixed(2);
document.getElementById('grandtotal').innerHTML = "<strong>Grand Total </strong>: $" + salesTotal*0.14 + salesTotal. toFixed(2);//grandtotal and tax total come out the same 
document.getElementById('discount').innerHTML = "<strong>Discount </strong>: $" + salesTotal*0.14 + salesTotal-discount.toFixed(2); //grandtotal and tax total come out the same 


<input name="discount" id="discount" type="number">

The period operator has higher precedence than the mathematical operators, so the toFixed method will be applied before the addition. 周期运算符的优先级高于数学运算符,因此toFixed方法将在加法之前应用。 As that makes the second operand a string, the + operator will do string concatenation instead of addition. 因为这使第二个操作数成为字符串,所以+运算符将进行字符串连接而不是加法。

You need parentheses to make the calculations happen before the toFixed call: 您需要括号使计算在toFixed调用之前进行:

(salesTotal * 0.13).toFixed(2)

(salesTotal * 0.14 + salesTotal).toFixed(2)

(salesTotal * 0.14 + salesTotal - discount).toFixed(2)

You are using 0.13 when calculating the tax, and 0.14 when calculating the total, they should probably be the same. 计算税收时使用的是0.13 ,计算总额时使用的是0.14 ,它们可能应该相同。

Instead of adding the total and the tax, you can just add one to the constant that you are multiplying with, ie salesTotal * 0.14 + salesTotal is the same as salesTotal * 1.14 . 无需将总数和税费相加,您只需在要乘以的常数上加一个,即salesTotal * 0.14 + salesTotalsalesTotal * 1.14相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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