Try my app Expense Manager @ google play and amazon store.

Friday, June 29, 2012

Java Script Tutorial 24 : JavaScript Math Object

The Math object allows you to perform mathematical tasks. The Math object includes several mathematical constants and methods. Syntax for using properties/methods of Math is as follows:


var x=Math.PI;
var y=Math.sqrt(16);


There is eight mathematical constants in JavaScript that can be accessed from the Math object. These mathematical constants 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
base-10 log of E.


We can call/reference these constants from JavaScript as below:


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


There are many mathematical methods also available in JavaScript. For example Math.round() is used to round a number, e.g  


document.write(Math.round(9.8));


Result of above code will be : 10


Math.random() method of the Math object is used to generate random numbers. For example


document.write(Math.random());


Result of above code can be anything between 0 and 1.


We can set the limit of random number generation( by using arguments ). For example, the following code return random number between 0 and 20.


Math.random()*21)


To generate random number from 0 and 100 change 21 to 101.

No comments:

Post a Comment

Follow by Email

Google+ Badge