我几乎有这个工作但是脚本正在舍入我的数字,而我希望保持两个小数位数的全价而不是自动向上舍入。这个脚本的沙箱在这里:
http://www.zacharydesigns.com/sandbox/calculatorJS2.html
这是代码:
<script type="text/javascript">
function update1() {
var a = +document.forms['calc'].elements['productOne'].value,
b = +document.forms['calc'].elements['productTwo'].value,
c = +document.forms['calc'].elements['productThree'].value,
productTotal = Math.floor(a/(a+b+c)*399.99);
document.forms['calc'].elements['productTotal1'].value = productTotal;
return false;
}
function update2() {
var a = +document.forms['calc'].elements['productOne'].value,
b = +document.forms['calc'].elements['productTwo'].value,
c = +document.forms['calc'].elements['productThree'].value,
productTotal = Math.floor(b/(a+b+c)*399.99);
document.forms['calc'].elements['productTotal2'].value = productTotal;
return false;
}
function update3() {
var a = +document.forms['calc'].elements['productOne'].value,
b = +document.forms['calc'].elements['productTwo'].value,
c = +document.forms['calc'].elements['productThree'].value,
productTotal = Math.floor(c/(a+b+c)*399.99);
document.forms['calc'].elements['productTotal3'].value = productTotal;
return false;
}
</script>
<form name="calc" action="#">
<table align="center"
border="1"><tr><td align="right">Boots: </td>
<td align="left"><input type="text" name="productOne" size="5" />
</td>
<td colspan="2" align="center">
<input type="button" value="Calculate"
onclick="update1();" /> </td>
<td align="right">Product Total:</td><td align="left">
<input type="text" name="productTotal1" size="6"
readonly="readonly" /></td>
</tr>
<tr>
<td align="right">Bindings: </td>
<td align="left"><input type="text" name="productTwo" size="5" />
</td>
<td colspan="2" align="center">
<input type="button" value="Calculate"
onclick="update2();" /> </td>
<td align="right">Product Total:</td><td align="left">
<input type="text" name="productTotal2" size="6"
readonly="readonly" /></td>
</tr><tr>
<td align="right">Boards: </td>
<td align="left"><input type="text" name="productThree" size="5" />
</td>
<td colspan="2" align="center">
<input type="button" value="Calculate"
onclick="update3();" /> </td>
<td align="right">Product Total:</td><td align="left">
<input type="text" name="productTotal3" size="6"
readonly="readonly" /></td>
</tr><tr></tr>
</tr>
</table></form>
有人可以告诉我如何在没有四舍五入的情况下对数字进行数学运算吗?
答案 0 :(得分:3)
我认为问题在于你正在使用楼层操作员。 floor函数总是向下舍入到最接近的整数,所以:
floor(3.5) == 3
floor(5.9999999999999999999999999999) = 5
floor(5) = 5
我认为你得到漂移。你想要做的是格式化小数位,toFixed()函数用于格式化。
所以基本上,改变这些行:
productTotal = Math.floor(c/(a+b+c)*399.99);
要:
productTotal = (c/(a+b+c)*399.99).toFixed(2);
我认为那就是你想要的。