javascript对象之——内置对象“Math”

Math对象的一些方法能实现我们课本上的某些数学计算,比较常用的方法有如下几个:

 

一、Math.min()和Math.max(),分别返回参数中的最小和最大值

  例:

  alert(Math.min(1,2,3))  //输出 “1”

  alert(Math.max(1,2,3))  //输出 “3”

 

二、Math.abs(),返回参数的绝对值

  例:

  alert(Math.abs(-1))  //输出 “1”

 

三、Math.random(),产生一个0到1的随机数

  例:

  window.open("http://www.***.com/index.shtml?t="+Math.random)  //在url地址后面加上一个值为随即数的参数,能保证页面每次都从服务器上重新拉取,而不是读取缓存。

 

四、Math.floor(),Math.round(),Math.ceil()

  Math.floor():把小数向下舍入成整数    例:alert(Math.floor(1.5))  //输出“1”

  Math.round():把小数标准四舍五入成整数  例:alert(Math.round(1.5))  //输出“2”

  Math.ceil():把小数向上舍入成整数  例:alert(Math.round(1.5))  //输出“2”

  利用这三个函数,在涉及小数计算的时候就非常方便,比如设计如下函数来进行小数处理

  function test(num,flag,bit)  //参数分别是 要传入的小数“num”   舍入标准(-1,向下;0,标准;1向上)“flag”  保留小数的位数“bit”

  {

    var n=Math.pow(10,bit);

    switch(flag)

    {

      case -1:return Math.floor(num*n)/n;break;

      case 0:return Math.round(num*n)/n;break;

      case 1:return Math.ceil(num*n)/n;

    }

  }

posted on 2010-04-06 21:36  唯C  阅读(175)  评论(0)    收藏  举报

导航