JAVASCRIPT: Math and Date Methods



The Math Class

The Math class contains a variety of static methods and constants that can be used by programmers for calculations and comparisons. All of the methods are called from the class name (Math). Each method takes at least one parameter, performs the required operations and then returns the result. The result can be either stored in a variable, output, or used in a calculation. Below are a few of the more commonly used Math class methods.
Square Root
returns the square root of a number
Math.sqrt(81);
9
Powers
returns the base (first number) raised to the power (second number)
Math.pow(2,3);
8
Minimum Value
returns the smaller of two or more numbers
Math.min(4,6);
Math.min(3,4,7,1);
4
Maximum
returns the larger of two or more values
Math.max(4,6);
Math.max(2,5,1,7);
6
Rounding
returns rounded value of the parameter (.5+ rounds up, under .5 rounds down)
Math.round(4.3);
Math.round(4.6);
4
5
Rounding Down
returns the next lowest integer (always rounds down)
Math.floor(4.3);
Math.foor(4.6);
4
4
Rounding Up
returns the next highest integer (always rounds up)
Math.ceil(4.3);
Math.ceil(4.6);
5
5
Absolute Value
returns the absolute value of a number - its positive distance from zero
Math.abs(-5);
Math.round(6);
5
6
Random Numbers
generates a random number between 0(inclusive) and 1.0 (exclusive)
Math.random();
.765849448
Pi
a constant variable that returns the value of Pi 3.1415...
Math.PI
3.1415...


Below are some examples of the Math methods and constants in action:

let radius=5; 
let diameter=2*radius;
let circumference=diameter*Math.PI;
document.getElementById('output').innerHTML=circumference;
In line (1), the value for radius could be obtained from input or another calculation. In line (2), the diameter is calculated and stored by doubling the radius. Then, the circumference is calculuated with the diameter and the PI constant. Finally, in line (4), the circumference value is output.
let radius=5; 
window.alert((Math.pow(radius, 2)*Math.PI);
This example calculates and outputs the value of the area of a circle in one line, as opposed to the step by step approach previously displayed in the circumference example. In line(2), the radius is rasied to the second power, then multiplied by PI and then output.
let a=3; 
let b=4;
let c=Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
document.getElementById('output').innerHTML+="c="+c;
This example uses the pythagorean theorem (a2 + b2 = c2) to find the missing hypotenuse of a right triangle. Notice how the pow functions are placed inside the sqrt function. This can also be done in separate steps if desired.


Random Numbers

The Math.random() function generates a value from 0 (inclusive) to 1.0 (exclusive). This can be represented in mathematics using interval notation. A square bracket, [ or ], means inclusive and a parenthesis, ( or ), means exclusive. So, the range of Math.random() can be represented as [0, 1).

So, to get different ranges, we need to do mathematical operations on the result of Math.random(). For example, if we do Math.random()*10, the range becomes [0, 10). If we add 1, we get [1, 11). Finally, if we cast the result as an int, we get only integer values
parseInt(Math.random()*10+1);


Limiting Decimals

Often, programmers find that they want to limit the number of decimals in the output of a calculation. Sometimes it is for display purposes so numbers line up, other times, it is due to the type of value they are calculations (money should be limited to two decimals).

JavaScript provides a toFixed() method that can be called from a variable that stores a number. The toFixed() method takes a parameter of the number of decimals that the programmers wants displayed.
let pi=3.1415;
window.alert(pi.toFixed(2));
The output of the above is 3.14.

BE CAREFUL - the toFixed method converts a number to a string ("3.14"). Be sure to do all of your calculations PRIOR to outputting the value.

The Date Class

JavaScript also provides a class that gives us functionality with the date. Most often, we are working with the current date, and creating a date variable accesses that information from the computer.

To get started with the date class methods, we need to create a Date variable that accesses the current date and time.
let today=new Date();


Once we have created a Date variable, we call the date methods from that variable. For our example, let's assume that we created this variable on Thursday, March 12, 2020 at 2:03.45pm. Using this information, look below for examples of some of the more common Date class methods.
Day of Week
returns the day of the week as a number where 0=Sunday and 6=Saturday
today.getDay();
5
Date in Month
returns the day of the month from 1-31
today.getDate();
12
Month
returns the month of the date with 0=January and 11=DecemberThis can easily be converted by adding 1 to the returned value
today.getMonth()
2
Year
returns the four digit year of the date
today.getFullYear();
2020
Hours
returns the hours of the time from 0-23 (military time)Hours can be converted using mathematics, specifically the modulus(%) operator
today.getHours();
14
Minutes
returns the minutes of the hour from 0-59
today.getMinutes();
3
Seconds
returns the seconds of the minute from 0-59
today.getSeconds();
45