Basic use[edit | edit source]
To make a new number, a simple initialization suffices:
var foo = 0; // or whatever number you want
foo = 1; //foo = 1 foo += 2; //foo = 3 (the two gets added on) foo -= 2; //foo = 1 (the two gets removed)
Number literals define the number value. In particular:
- They appear as a set of digits of varying length.
- Negative literal numbers have a minus sign before the digits.
- Floating point literal numbers contain one decimal point, and may optionally use the e notation with the character e.
- An integer literal may be prepended with "0" to indicate that a number is in base-8. (8 and 9 are not octal digits, and if found, cause the integer to be read in the normal base-10).
- An integer literal may also be found with prefixed "0x" to indicate a hexadecimal number.
The Math object[edit | edit source]
var varOne = Math.ceil(8.5); var varPi = Math.PI; var sqrt3 = Math.sqrt(3);
Methods[edit | edit source]
ceil(float)[edit | edit source]
Returns the least integer greater than the number passed as an argument.
var myInt = Math.ceil(90.8); document.write(myInt); //91;
floor(float)[edit | edit source]
Returns the greatest integer less than the number passed as an argument.
var myInt = Math.floor(90.8); document.write(myInt); //90;
max(int1, int2)[edit | edit source]
Returns the highest number from the two numbers passed as arguments.
var myInt = Math.max(8, 9); document.write(myInt); //9
min(int1, int2)[edit | edit source]
Returns the lowest number from the two numbers passed as arguments.
var myInt = Math.min(8, 9); document.write(myInt); //8
random()[edit | edit source]
Generates a pseudo-random number.
var myInt = Math.random();
round(float)[edit | edit source]
Returns the closest integer to the number passed as an argument.
var myInt = Math.round(90.8); document.write(myInt); //91;
parseInt() and parseFloat()[edit | edit source]
var x = parseInt("7.5") + 4; console.log(x); //7 + 4 = 11. var y = parseFloat("2.8") + 3; console.log(y); //2.8 + 3 = 5.6. var z = parseInt("Cat"); console.log(z); // NaN
Properties[edit | edit source]
Properties of the Math object are most commonly used constants or functions:
- E: Returns the constant e.
- PI: Returns the value of pi.
- LN10: Returns the natural logarithm of 10.
- LN2: Returns the natural logarithm of 2.
- SQRT2: Returns the square root of 2.