Detailed explanation of JS Math object and random number method (there is a formula worth looking at)

Detailed explanation of JSMath object and random number method

The detailed explanation of the Math object of JS, in the development process, is sometimes more commonly used, and it is also very convenient to use, especially when probabilistic judgment is sometimes required, such as lottery, which can be cleverly used by the method of this object. The probability can also be well controlled. Here I will summarize some of the more practical things for everyone. Maybe I use the vernacular, and the expression is not very good, not very professional, but it’s okay, as long as everyone can understand it.

The value in parentheses indicates the value we need to participate in the operation;

Math.abs (value);: Means to take the absolute value.

Math.ceil (value);: Round up, add 1 to the value in parentheses if there is a decimal.

Math.floor (value); round down, take the integer part of the value, and omit the decimal.

Math.max (value 1, value 2) ; take the largest number and return the largest value in the parameter. There can be multiple values ​​and not only two values.

Math.max(value 1, value 2) ; take the small or large number and return the smallest value in the parameter. There can be multiple values, not only two values.

Math.round (value); round the value in parentheses;

Math.random(); returns a random number between 0 and 1, but not including 1; note that this method has no parameters.

A very useful formula for taking random numbers, returning a value between the smallest number and the largest number:
Math.floor(Math.random()*(maximum-minimum+1)+minimum);
For example: we need Take a number between 10 and 50, then write 50 for the maximum value and 10 for the minimum value;

If friends who don’t understand the text look at the code, the code is as follows:

   
   //1.向下取整
   var floor = Math.floor(1.56);
   //运行结果:1
   
   //2.向上取整
   var ceil = Math.ceil(1.52);
    //运行结果:2
    
   //3.四舍五入
   var round
    = Math.round(1.57);
    //运行结果:2
    
   //.4取最大数
   var max =Math.max(1,2,6);
    //运行结果:6
    
   //.5取最小数
   var min =Math.max(1,2,6);
    //运行结果:1
   
   //.6取绝对值
   var abs=Math.abs(-5);
    //运行结果:5
   
   //.7取随机数,返回一个0~1之间1的数,但是不会包括1
   var random=Math.random();
   //运行结果:0.3777896747357721
    document.write(random);
    
//.8取随机数公式: Math.floor(Math.random()*(最大数-最小数+1)+最小数)
//还有很多其他取随机数的方式,但是有了这个公式其他的我就不多说了,这挺好用的。
   var num= Math.floor(Math.random()*(50-10+1)+10);
   //运行结果:14
  
  </script>
 </body>
</html>

Guess you like

Origin blog.csdn.net/m0_46188681/article/details/106004672
Recommended