<html>
<script>
function round (n, d) {
  var t = n < 0 ? "-":"";
  n = Math.abs(n) - 0;
  d = d || 2;
  var f = Math.pow(10, d);
  n = Math.round(n * f) / f;
  n += Math.pow(10, - (d + 1));
  n += '';
  return d == 0 ? t+n.substring(0, n.indexOf('.')) :
      t+n.substring(0, n.indexOf('.') + d + 1);
}
</script>
<body><script type="text/javascript">
document.writeln(round(3.65*97/100,3));
document.writeln(round(3.65*(97/100),3));document.writeln(round(0.435*90/100,3));
document.writeln(round(0.435*(90/100),3));</script>
</body>
</html>
按正常的四舍五入,正确答案应该是1,4
现在问题出来了,我到底应该按哪种运算顺序来呢?
 JS银行家JS 银行家浮点运算四舍五入

解决方案 »

  1.   

    按你的脚本,在Firefox下运行结果是3.541 3.540 0.391 0.392 
    <html>
    <script>
    function round (n, d0) {
      var d = d0+1;
      var t = n < 0 ? "-":"";
      n = Math.abs(n) - 0;
      d = d || 2;
      var f = Math.pow(10, d);
      n = Math.round(n * f) / f;
      n += Math.pow(10, - (d + 1));
      n += '';
      return d == 0 ? t+n.substring(0, n.indexOf('.')) :
          t+n.substring(0, n.indexOf('.') + d + 1);
    }
    </script>
    <body>
     
    <script type="text/javascript">
    document.writeln(round(3.65*97/100,3));
    document.writeln(round(3.65*(97/100),3));
     
    document.writeln(round(0.435*90/100,3));
    document.writeln(round(0.435*(90/100),3));
     
    </script>
    </body>
    </html>
    之后:运行结果是3.5405 3.5405 0.3915 0.3915 
    尽量避开浮点数乘除,其中涉及到小数转换成二进制的失真。
    (其实我认为就像无限循环小数,要用无穷多为才能表示,计算机又没有那么多位,肯定会失真了)