<head>
<title>Javascript Test</title>
</head>
<body>
<script>
function calc_form() {
discPerc = document.forms["calc"].elements["disc_perc"].value;
totDays = document.forms["calc"].elements["tot_days"].value;
discPer = document.forms["calc"].elements["disc_per"].value;
discDays = document.forms["calc"].elements["disc_days"].value;
discCalc = Math.round([(discPerc/100)/((100-discPerc)/100)]*(totDays/(discPer-discDays)));
document.forms["calc"].elements["result"].value = discCalc*100 + "%";
document.getElementById("result1").innerHTML = discCalc*100 + "%";
//return Math.round(discCalc);
}
</script>
<form name = "calc">
Discount Percentage:
<br>
<input type = "text" name="disc_perc">
<br>
Enter Total Days in a year:
<br>
<input type="text" name="tot_days">
<br>
Enter Discount Days:
<br>
<input type="text" name="disc_days">
<br>
Enter Discount Period
<br>
<input type="text" name="disc_per">
<input type="button" value="Calculate" onclick = "calc_form()">
<br> <br>
Cost of forgoing discount:
<br>
<input type="text" id="result">
</form>
<p id="result1"></p>
</body>
以上代码产生意外结果。当然,它有一个错误,但我无法理解。当我在Math.round函数中包含discCalc变量时,输出完全不同于我没有。
请有人解释这种差异。
谢谢。
答案 0 :(得分:0)
我只是通过使用variable.toFixed(2)而不是使用Math.round()函数来解决问题。所以代码是:
<script>
function calc_form() {
discPerc = document.forms["calc"].elements["disc_perc"].value;
totDays = document.forms["calc"].elements["tot_days"].value;
discPer = document.forms["calc"].elements["disc_per"].value;
discDays = document.forms["calc"].elements["disc_days"].value;
//discCalc = Math.round([(discPerc/100)/((100-discPerc)/100)]*(totDays/(discPer-discDays)));
discCalc = [(discPerc)/((100-discPerc))]*(totDays/(discPer-discDays));
discCalc_2 = discCalc*100;
document.forms["calc"].elements["result"].value = discCalc_2.toFixed(2) + "%";
document.getElementById("result1").innerHTML = discCalc_2.toFixed(2) + "%";
//return Math.round(discCalc);
}
</script>
<form name = "calc">
Discount Percentage:
<br>
<input type = "text" name="disc_perc">
<br>
Enter Total Days in a year:
<br>
<input type="text" name="tot_days">
<br>
Enter Discount Days:
<br>
<input type="text" name="disc_days">
<br>
Enter Discount Period
<br>
<input type="text" name="disc_per">
<input type="button" value="Calculate" onclick = "calc_form()">
<br> <br>
Cost of forgoing discount:
<br>
<input type="text" id="result">
</form>
<p id="result1"></p>