JavaScript Math Object
Previous | Table of Contents | Next |
JavaScript Date Object | JavaScript Window Object |
<google>BUY_JAVASCRIPT</google>
The JavaScript Math object provides a collection of mathematical constants and methods for performing such tasks as generating random numbers, rounding, obtaining values such as PI and performing calculations.
JavaScript Math Object Methods
The following table lists the methods available with the Math object:
Method | Description |
---|---|
abs | Absolute value |
sin, cos, tan | Standard trigonometric functions; argument in radians |
acos, asin, atan, atan2 | Inverse trigonometric functions; return values in radians |
exp, log | Exponential and natural logarithm, base e |
ceil | Returns least integer greater than or equal to argument |
floor | Returns greatest integer less than or equal to argument |
min, max | Returns greater or lesser (respectively) of two arguments |
pow | Exponential; first argument is base, second is exponent |
random | Returns a random number between 0 and 1. |
round | Rounds argument to nearest integer |
sqrt | Square root |
JavaScript Math Object Properties
In addition the math object contains a number of properties for accessing mathematical constants:
Property | Description |
---|---|
E | Euler's constant |
LN2 | Natural log of 2 |
LN10 | Natural log of 10 |
LOG2E | Log base -2 of E |
LOG10E | Log base -10 of E |
PI | Value of Pi |
SQRT1_2 | Square root of 0.5 |
SQRT2 | Square root of 2 |
Using JavaScript Math Object and Properties
The first thing to be aware of with the Math object is that an instance of the object already exists. It is not necessary, therefore, to create a new instance using the new keyword. You can simply access the methods and properties by referencing Math.
The methods and properties of the JavaScript Math object can be accessed just as with any other objects (see JavaScript Object Basics for more information). For example we can obtain the value of Pi:
Math.Pi;
We can perform square root calculation:
Math.sqrt(3);
Rounding and Truncating Numbers with the the Math Object
The ceil(), floor() and round() methods of the JavaScript Math object can be used to round numbers up and down:
Math.ceil() - Rounds a number up to the nearest integer
Math.floor() - Rounds a number down to the nearest integer
Math.round() - Rounds a number to the nearest integer (i.e up or down depending on which is closest)
Each of the above methods takes a number as an argument and returns the modified value:
var rounded = Math.round(8.87);
<google>BUY_JAVASCRIPT_BOTTOM</google>
Previous | Table of Contents | Next |
JavaScript Date Object | JavaScript Window Object |