function fixTo(s,i){
if (s==null || s=="" || isNaN(s) || Math.round(s)==0) return 0;
i = Math.round(i);
if (i==0) return Math.round(s);
if (i==null || isNaN(i) || i<0) i=2;
var v = Math.round(s*Math.pow(10,i)).toString();
if (/e/i.test(v)) return s;
return v.substr(0,v.length-i)+"."+v.substr(v.length-i);
}
alert(fixTo(1234.1234))
alert(fixTo(1234.1234,1))
alert(fixTo(1234.1234,10))
alert(fixTo(1234.1234,20))
alert(fixTo(1234.1234,0))
alert(fixTo(123456782))

解决方案 »

  1.   

    <script>
    Number.prototype.fix = function(num)
      {with(Math)return round(this.valueOf()*pow(10,num))/pow(10,num)
      }
    alert(2.1234567898.fix(2));
    alert(12.67898.fix(1));
    alert(12.56456.fix(4));
    </script>
      

  2.   

    IE5.5以上直接有方法:
    alert(12.12348.Fixed(2))
      

  3.   

    最简单的办法就是
    <script>
    aa=23.344423426
    alert(aa.toFixed(2));
    alert(aa.toFixed(5))
    </script>
    精确到多少位就带参数几 yourNumber.toFixed(n)
      

  4.   

    非常感谢大家的捧场,给分了,并且给出给分理由.
    to:emu_ston(人笨,是一辈子的事);xinyunyishui(心云意水)
    alert(12.12348.Fixed(2))方法通不过.
    抱歉,在这个问题上不能给分.因为不是最简单的.
    不过回另外给分了.
    to: zhjzh_zjz(虚心学习,望多指教)
    50分.完全符合要求.
      

  5.   

    没分事小,对错事大!
    coaa(我吃多了),你可以试试看用zhjzh_zjz(虚心学习,望多指教)的方法在IE5.0下检测一下!如果你只考虑5.5+以上就算了,否则,只要你考虑5.0,估计你就又要开帖子问:toFixd(n)不能在5.0中使用,如何解决???
    这种问题!
    对了,我的第二个帖子中你说不能通过,的确没错,因为我把alert(12.12348.toFixed(2))手误,错打成了alert(12.12348.Fixed(2))
      

  6.   

    呵呵。分没什么用的。不过我的函数调用方式是:alert(fixTo(12.12348,2))不用protytype是因为NS不支持这样的写法。写的那么复杂是为了在要求精度大于数值的实际精度时可以补0:alert(fixTo(12.1,2))
      

  7.   

    to emu_ston(人笨,是一辈子的事):补0?呵呵~~,那个我也写了满复杂的东西,在这个帖子里。
    http://expert.csdn.net/Expert/topic/1594/1594039.xml?temp=.3157465
    嗯,由于一直不做ns的东西,所以就没有考虑那么多的东西。