Simple JavaScript Math Function Use randomly
Math
is a built-in object. It has properties and methods for mathematical constants and functions. It’s not a function object.
Math
works with the number type. It doesn't work with BigInt.
Unlike many other global objects, Math
is not a constructor. All properties and methods of Math
are static. You refer to the constant pi as Math.PI
and you call the cosine function as Math.cos(
x)
, where x is the method’s argument. Constants are defined with the full precision of real numbers in JavaScript.
Math.abs()
abs()
is a static method of Math
, you always use it as Math.abs()
, rather than as a method of a Math
object created.
Behavior of abs() :
Math.abs(‘-1’); // 1
Math.abs(-2); // 2
Math.abs(null); // 0
Math.abs(‘’); // 0
Math.abs([]); // 0
Math.abs([2]); // 2
Math.abs([1,2]); // NaN
Math.abs({}); // NaN
Math.abs(‘string’); // NaN
Math.abs(); // NaN
Math.floor()
floor()
is a static method of Math
, you always use it as Math.floor()
, rather than as a method of a Math
object created
Behavior of floor() :
var a = Math.floor(0.60); //0
var b = Math.floor(0.40); //0
var c = Math.floor(5); //5
var d = Math.floor(5.1); //5
var e = Math.floor(-5.1); //-6
var f = Math.floor(-5.9); //-6
Math.ceil()
ceil()
is a static method of Math
, you always use it as Math.ceil()
, rather than as a method of a Math
object created
Behavior of ceil()
:
Math.ceil(.95); // 1
Math.ceil(4); // 4
Math.ceil(7.004); // 8
Math.ceil(-0.95); // -0
Math.ceil(-4); // -4
Math.ceil(-7.004); // -7
Math.random();
Return a random number between 0 (inclusive) and 1 (exclusive).
Behavior of random() :
Return a random number between 1 and 10:
Math.floor((Math.random() * 10) + 1);
Return a random number between 1 and 100:
Math.floor((Math.random() * 100) + 1);
Math.round()
The round() method rounds a number to the nearest integer.
Behavior of round():
var a = Math.round(2.60); // 3
var b = Math.round(2.50); // 3
var c = Math.round(2.49); //2
var d = Math.round(-2.60); //-3
var e = Math.round(-2.50); //-2
var f = Math.round(-2.49); //-2