HTML and CSS Reference
In-Depth Information
Using Number Constants and Different Bases.
The constants
MAX_VALUE
,
MIN_VALUE
,
NEGATIVE_INFINITY
,
POSITIVE_INFINITY
, and
NaN
are properties of
the
Number()
function, but are not used with instances of the
Number
object; thus,
var
huge = Number.MAX_VALUE
is valid, but
huge.MAX_VALUE
is not.
NaN
is a special
value that is returned when some mathematical operation results in a value that is not
a number.
The methods provided to the
Number
object manipulate instances of number objects.
For example, to convert numbers to strings representing different bases, the
toString()
method manipulates a number, either primitive or object. See Example 9.31.
EXAMPLE
9.31
<html>
<head><title>Number Contants</title></head>
<body bgcolor="orange"><font color="black" size="+1">
<h2>Constants</h2>
<script type="text/javascript">
1
var largest = Number.MAX_VALUE;
2
var smallest = Number.MIN_VALUE;
3
var num1 = 20;
//
A primitive numeric value
4
var num2 = new Number(13);
//
Creating a Number object
document.write("<b>The largest number is " +
largest
+ "<br />");
document.write("The smallest number is "+
smallest
+ "<br />");
5
document.write("The number as a string (base 2): "+
num1.toString(2)
);
6
document.write("<br />The number as a string (base 8): "+
num2.toString(8)
);
7
document.write("<br />The square root of -25 is: "+
Math.sqrt(-25)
+ "<br />");
</script>
</body>
</html>
EXPLANATION
1
The constant
MAX_VALUE
is a property of the
Number()
function. This constant
cannot be used with an instance of a
Number
object.
2
The constant
MIN_VALUE
is a property of the
Number()
function.
3
A number is assigned to the variable called
num1
.
4
A new
Number
object is created with the
Number()
constructor and assigned to
num2
. It is easier to use the literal notation:
num2 = 13
.
5
The number is converted to a string represented in binary, base 2.
6
The number is converted to a string represented in octal, base 8.
7
The square root of a negative number is illegal. JavaScript returns
NaN
, not a
number, when this calculation is attempted (see Figure 9.36).