这包括两个问题。第一个问题是将数字四舍五入到某个小数点。第二个问题是将下拉菜单连接到正确的小数。
首先是我的代码:
<style>
span{font-style:italic;}
span{color:green;}
</style>
<script>
function calcul(){
var sales = parseFloat(document.getElementById("sales").value);
var OpExp = parseFloat(document.getElementById("OpExp").value);
var TaxAll = parseFloat(document.getElementById("TaxAll").value);
var Depre = parseFloat(document.getElementById("Depre").value);
var Divid = parseFloat(document.getElementById("Divid").value);
var TaxR = parseFloat(document.getElementById("TaxR").value);
//GP = Gross Profit
var GP = sales - OpExp;
//TaxInc = Taxable Income
var TaxInc = GP + TaxAll;
//NetInc = Net Income
var NetInc = TaxInc - ((TaxR / 100) * TaxInc);
document.getElementById("NetIncome").innerHTML=
TaxInc - ((TaxR / 100) * TaxInc);
//AtRE = Addition to Retained Earnings
document.getElementById("AtRE").innerHTML = NetInc - Divid;
}
</script>
<form action="" id="nothing">
In 2007 the British building firm Balfour Betty plc had sales of
<input type="text" id="sales" maxlength="6" size="6">
million, total operating expenses of
<input type="text" id="OpExp" maxlength="6" size="6">
million, a tax allowance (rebate) of
<input type="text" id="TaxAll" maxlength="6" size="6">
million because of past losses, and
<input type="text" id="Depre" maxlength="6" size="6">
depreciation. <strong>What is the net income of the
firm?</strong><br />
<br />
Balfour Betty plc paid out <input type="text" id="Divid" maxlength="6" size="6"> million
in cash dividends. <strong>What is the addition to retained earnings?</strong><br />
<br />
The tax rate is <input type="text" id="TaxR" maxlength="6" size="6"> %.<br />
<br />
<input type="button" value="Calculate" id="but" onclick="calcul()" /><br />
<br />
</form>
<strong>The Net Income of Balfour Betty plc is </strong><span id="NetIncome">XXX</span>
<strong> million</strong><br />
<br />
<strong>The addition to retained earnings of Balfour Betty plc is </strong><span id="AtRE">
XXX</span><strong> million</strong>
<br />
<br />
第一个问题:舍入数字。以下答案:<span id="NetIncome">
需要动态舍入。我尝试添加一个名为RNetInc
的新变量并添加以下等式RNetInc = NetInc.toFixed(4)
,但它只给了我两个小数,并且在刷新之后它甚至不再起作用了。将答案舍入N个小数的最佳方法是什么?
第二个问题是我不知道是否可能。我的想法如下: 下拉菜单
<select>
<option value"1">1 decimal</option>
<option value"2">2 decimals</option>
<option value"3">3 decimals</option>
</select>
所以,我想要的是当我点击N decimal
时,答案将变为N十进制。这是一个非常复杂的情况,但我经常需要这样的情况。
由于我只知道Javascript的(非常)基础知识,即使使用Google我也找不到答案。有人能让我走上正轨(如果可能的话)?提前谢谢。
答案 0 :(得分:1)
我建议只修复最终结果,toFixed()
返回一个字符串。
select
的HTML:
<select id="dec">
<option value="1">1 decimal</option>
<option value="2">2 decimals</option>
<option value="3">3 decimals</option>
</select>
在calcul()
:
var decs = +(document.getElementById('dec').value); // Add this line
document.getElementById("NetIncome").innerHTML = (TaxInc - ((TaxR / 100) * TaxInc)).toFixed(decs);
document.getElementById("AtRE").innerHTML = (NetInc - Divid).toFixed(decs);
A live demo at jsFiddle(已更新)。
修改强>
看起来我部分误解了你的问题。请检查更新的小提琴,现在您也可以通过从select
中选择一个值来随时更改小数位数。