Math object

JavaScript topics covered: click here for a complete list of Math Constants and Functions.
  1. Math Properties

    There is more to JavaScript than your basic arithmatic operations like adding and subtracting. JavaScript supports scientific notation along with complex mathmatical operations. These can be found in the Math object. You do not have to define a Math object before using it. There are eight mathematical constants (properties) that can be accessed from the Math object. These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E.

    Math.E
    Math.LN2
    Math.LN10
    Math.LOG2E
    Math.LOG10E 
    Math.PI
    Math.SQRT2
    Math.SQRT1_2
    
  2. Math Methods

    Javascript also has many functions (methods). Some of the more popular are:

    Math.ceil()
    Math.floor()
    Math.min()
    Math.max()
    Math.pow()
    Math.random()
    Math.round()
    
  3. Practical Examples

    The example below formats a number to the number of decimal places needed

    function fix(numToFix, decimalPlaces){
    if(isNaN(fixNumber)) 	return 0;
    var div = Math.pow(10, decimalPlaces);	//calculate 10 to the power of the number of decimal places needed
    numToFix = Math.round(numToFix * div)/div;	//multiply the original number by 10^x, round, then Divide by 10^x;
    var string = numToFix.toString();	//convert the number to a string variable
    	var parts = string.split(".");	//create an array with the dollars in one part the cents in the other
    	var cents = parts[1];
    	while (cents.length<decimalPlaces)	//add as many zeros as needed
    	     cents += "0";
    	return parts[0]+"."+cents		//return the formatted number
    }
    
    
    Click here to see the demo



    Random used to randomly display an image

    Math.random() returns a number between 0.0 and 1.0
    Math.floor() rounds the number down, removing any decimal places

    In the example below, multiply the random number by the length of the array, this will return a number less than the the length of the array. In the example below that would be a number greater than 0 but less than 3, like 1.3906894. Using Math.floor removes the decimal places leaving an integer, like 1. The integer can then be used as an index for the array, like img[1].

    
    var img = new Array("/images/character0.gif","/images/character1.gif","/images/character2.gif" );
    var numOfImages = img.length;
    
    function getImage(){
    var randomNum = Math.random() * numOfImages;  //get a number between 0 and 3
    var imageNum = Math.floor(randomNum);	//remove decimal places 
    document.images[0].src=img[imageNum];	//use the number as an index
    }
    
    Click here to see the demo