HTML and CSS Reference
In-Depth Information
The value displayed in the
daysLeft
field is 310.3923…, indicating that slightly more
than 310 days are left until the start of the New Year's Bash based on the value you
inserted in the
today
variable. The fractional part of the value represents how much of the
last day is remaining until midnight on New Year's Eve. Because Hector is interested only
in the integer number of days, hours, minutes, and seconds until the party begins, you
have to modify this value by extracting the days amount and then converting the frac-
tional part to hours, minutes, and seconds. You can do this by using some of the built-in
JavaScript functions for mathematical calculations.
Working with the
Math
Object
One way of performing these types of calculations is to use JavaScript's
Math
object.
The
Math
object
is an object that can be used to perform mathematical tasks and store
mathematical values.
Using
Math
Methods
The
Math
object supports several different
Math
methods
, which store functions used
for performing advanced calculations and mathematical operations such as generating
random numbers, extracting square roots, and calculating trigonometric values. The syn-
tax for applying a
Math
method is
Math.
method
(
expression
)
where
method
is the method you'll apply to a mathematical
expression
. For example,
the following code calculates the square root of 10, storing that value in the y variable:
Case is important when
applying the
Math
object;
you must use
Math
instead of
math
when
applying this object.
var x = 10;
var y = Math.sqrt(x)
Figure 11-20 lists the JavaScript
Math
methods and describes how to apply them.
Figure 11-20
Methods of the Math object
Math
Method
Returns
Math.abs(
x
)
the absolute value of
x
Math.acos(
x
)
the arc cosine of
x
in radians
Math.asin(
x
)
the arc sine of
x
in radians
Math.atan(
x
)
the arc tangent of
x
in radians
Math.atan2(
x, y
)
the angle between the
x
-axis and the point (
x, y
)
Math.ceil(
x
)
x
rounded up to the next highest integer
Math.cos(
x
)
the cosine of
x
Math.exp(
x
)
e
x
Math.floor(
x
)
x
rounded down to the next lowest integer
Math.log(
x
)
the natural logarithm of
x
the larger of
x
and
y
Math.max(
x
,
y
)
Math.min(
x
,
y
)
the smaller of
x
and
y
x
y
Math.pow(
x
,
y
)
Math.random()
a random number between 0 and 1
Math.round(
x
)
x
rounded to the nearest integer
Math.sin(
x
)
the sine of
x
Math.sqrt(
x
)
the square root of
x
Math.tan(
x
)
the tangent of
x