The JS rounded up, rounding down, rounding, etc.

  • Retaining only the integer part (decimal part is discarded)
parseInt(5.1234);      // 5
  • Rounding down (largest integer <= the numerical value, and the parseInt () as)
Math.floor(5.1234);     // 5    
  • Rounding up (with decimal integer part to +1)
Math.ceil(5.1234);     // 6
  • Rounding (fractional part)
Math.round(5.1234);      // 5
Math.round(5.6789);     // 6
  • Absolute value
Math.abs(-1);      // 1
  • Returns the larger of two numbers
Math.max(1,2);     // 2
  • Returns the smaller of two numbers
Math.min(1,2);    // 1
  • Random Number (0-1)
Math.random();  //返回 0(包括) 至 1(不包括) 之间的随机数
JavaScript random integer

Used together Math.random () and Math.floor () returns a random integer.

Math.floor(Math.random() * 10);     // 返回 0 至 9 之间的数 
Math.floor(Math.random() * 11);     // 返回 0 至 10 之间的数
Math.floor(Math.random() * 100);    // 返回 0 至 99 之间的数
Math.floor(Math.random() * 101);    // 返回 0 至 100 之间的数
Math.floor(Math.random() * 10) + 1; // 返回 1 至 10 之间的数
Math.floor(Math.random() * 100) + 1;    // 返回 1 至 100 之间的数

An appropriate random function
As you can see from the above example, create a random function is used to generate all the random integer is a good idea.

This JavaScript function always returns a random number between min (including) and max (not included) between:

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min) ) + min;
}

This JavaScript function always returns a random number between min and max (both included) between:

function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}

Original: https://www.jianshu.com/p/a93bd02d9eb7

Guess you like

Origin www.cnblogs.com/jessie-xian/p/11576374.html