数学对象math取整方法

220 阅读1分钟
Math.ceil 向上舍入
   <script>
    // Math.ceil()向上舍入
    var num= Math.ceil(25.3)  //当Math.ceil()是正数时且有小数点时,返回的值则+1取整
                              //此时Math.ceil()的值是26
    document.write(num)   

image.png

当Math.ceil()是负数时且有小数点时:

         <script>
    // Math.ceil()向上舍入
    var num = Math.ceil(-25.8)  //当Math.ceil()是负数时且有小数点时,
                             //返回的值是当前值且去除小数点后面的数,此时Math.ceil()的值是25
    document.write(num)
</script>

image.png

Math.floor 向下舍入
   <script>
    // Math.floor()向下舍入
    var num = Math.floor(25.8)  //当Math.floor()是正数时且有小数点时,
                                //返回的值是当前值且去除小数点后面的数,此时Math.floor()的值是25
    document.write(num)
</script>

image.png 当Math.floor()是负数时且有小数点时:

<script>
    // Math.floor()向下舍入
    var num = Math.floor(-25.8)  //当Math.floor()是负数数时且有小数点时,
                                  //返回的值是当前值加上-1且去除小数点后面的数,
                                  //此时Math.floor()的值是-26
    document.write(num)
    

image.png

Math.round()四舍五入
    <script>
    // Math.round()四舍五入
    var num = Math.round(25.4)  //当Math.round()是正数且有小数点,
                                 // 遵循四舍五入的原则

    document.write(num)          //返回值是25
</script>

image.png

     <script>
    // Math.round()四舍五入
    var num = Math.round(-25.5)  //当Math.round()是负数且有小数点,
                                 // 如小数点后的数小于6时遵循四舍的原则

    document.write(num)          //返回值是25
</script>

image.png

重点来了:

     <script>
    // Math.round()四舍五入
    var num = Math.round(-25.6)  //当Math.round()是负数且有小数点,
                                 // 如小数点后的数大于5时,返回的值是当前值+(-1)

    document.write(num)          //返回值是26
</script>

image.png

Math.randon()随机数 范围在0~1.0之间,但是不包括1

image.png

Math.pow次方

Math.pow(自定义值,自定义值的几次方)

     <script>
    // Math.pow(自定义值,自定义值的几次方)
    var num = Math.pow(2,3)           

    document.write(num)          //返回值是2的3次方=8
</script>   

image.png

随机抽取数组的数据的公式
  <script>
  Math.floor(Math.random()*(max-min+1))+min
</script>

接下来我们用这个公式来做个案例:

建立一个数组里面含有1到5等奖,利用随机进行抽奖。

     <body>
<button onclick="fn()">点击抽奖</button>
<script>
    function fn() {
        var arr = [ '一等奖', '二等奖', '三等奖', '四等奖', '五等奖']
        var num = Math.floor(Math.random() * (5 - 0 + 1)) + 0;
        document.write(`恭喜获得${arr[num]}`);
    }
</script>
</body>

image.png

image.png