HTML and CSS Reference
In-Depth Information
Figure 11-21
Properties of the Math object
Math
Constant
Description
Math.E
The natural logarithm base,
e
(approximately 2.7183)
Math.LN10
The natural logarithm of 10 (approximately 2.3026)
The natural logarithm of 2 (approximately 0.6931)
Math.LN2
Math.LOG10E
The base 10 logarithm of
e
(approximately 0.4343)
Math.LOG2E
The base 2 logarithm of
e
(approximately 1.4427)
Math.PI
The value
(approximately 3.1416)
p
Math.SQRT1_2
The value of 1 divided by the square root of 2 (approximately 0.7071)
Math.SQRT2
The value of the square root of 2 (approximately 1.4142)
For example, the formula to calculate the volume of a sphere is 4π
r
3
/3, where
r
is the
radius of the sphere. To reference the value of π in the calculation of a sphere's vol-
ume, you would apply the
Math.PI
constant. To cube the value of
r
, you would use the
method
Math.pow(
r
, 3)
. Putting these together, a function to return the volume of a
sphere given the radius is:
function sphereVolume(radius) {
volume = 4*Math.PI*Math.pow(radius, 3)/3;
return volume;
}
To calculate the volume of a sphere that is two units in radius, you could then enter the
expression
var x = sphereVolume(2);
and JavaScript would assign a value of 33.5103 to the
x
variable.
You don't need to use any
Math
object constants for the New Year's Bash Web site.
However, the countdown clock needs to display only the integer portion of the days left
in the year. You can calculate this value using the
Math.floor()
method, which rounds
a value down to the next lowest integer. For the days left value of
310.39…
currently in
the countdown clock, this method returns the integer value
310
. You'll apply this method
to the value displayed in the daysLeft field.
To apply the
Math.floor()
method:
◗
1.
Return to the
clock.htm
file and the NYClock() function in your text editor.
◗
2.
Change the statement that sets the value of the
daysLeft
field to the following two
lines, as shown in Figure 11-22:
// display days rounded to the next lowest integer
document.clockform.daysLeft.value = Math.floor(days) + “ day(s)”;