我几乎可以正常工作了,但是脚本正在四舍五入,而我希望保留两个小数位的全额价格,而不是自动四舍五入。我的脚本脚本沙箱在这里:

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>


有人可以告诉我如何对整数进行数学运算而不四舍五入吗?

最佳答案

我认为问题在于您正在使用发言权操作员。楼层运算符始终四舍五入到最接近的整数,因此:

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);


我认为这将是您想要的。

关于javascript - JavaScript数学显示小数位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1640522/

10-12 06:57