Book Image

Object-Oriented JavaScript

Book Image

Object-Oriented JavaScript

Overview of this book

Table of Contents (18 chapters)
Object-Oriented JavaScript
Credits
About the Author
About the Reviewers
Preface
Built-in Functions
Regular Expressions
Index

Number


Creates number objects:

>>> var n = new Number(101);
>>> typeof n

"object"

>>> n.valueOf();

101

Number objects are not primitive objects, but if you use a number method on a primitive number, the primitive will be converted to a Number object behind the scenes and the code will work.

>>> var n = 123;
>>> typeof n;

"number"

>>> n.toString()

"123"

Members of the Number Constructor

Property/Method

Description

Number.MAX_VALUE

A constant property (cannot be changed) that contains the maximum allowed number.

>>> Number.MAX_VALUE

1.7976931348623157e+308

>>> Number.MAX_VALUE = 101;

Number.MAX_VALUE is read-only

Number.MIN_VALUE

The smallest number you can work with in JavaScript.

>>> Number.MIN_VALUE

5e-324

Number.NaN

Contains the Not A Number number.

>>> Number.NaN 

NaN

NaN is not equal to anything including itself.

>>> Number.NaN === NaN 

false

Number.NaN is more reliable than simply using NaN, because the latter can be overwritten by mistake.

>>> NaN = 1; // don't do this!

1

>>> NaN 

1

>>> Number.NaN 

NaN

Number.POSITIVE_INFINITY

Contains the Infinity number. This is more reliable than the global Infinity value (property of the global object) because it is read-only.

Number.NEGATIVE_INFINITY

Has the value -Infinity. See above.

Members of the Number Objects

Property/Method

Description

toFixed(fractionDigits)

Fixed-point representation of a number object as a string. Rounds the returned value.

>>> var n = new Number(Math.PI);
>>> n.valueOf();

3.141592653589793

>>> n.toFixed(3)

"3.142"

toExponential(fractionDigits)

Exponential notation of a number object as a string. Rounds the returned value.

>>> var n = new Number(56789);
>>> n.toExponential(2)

"5.68e+4"

toPrecision(precision)

String representation of a number object, either exponential or fixed-point, depending on the number object.

>>> var n = new Number(56789);
>>> n.toPrecision(2)

"5.7e+4"

>>> n.toPrecision(5)

"56789"

>>> n.toPrecision(4)

"5.679e+4"

>>> var n = new Number(Math.PI);
>>> n.toPrecision(4)

"3.142"