You are here: Reference > JavaScript > core > objects > Number

Number object

Browser support:
Represents a numeric value as an object.

The Number object supports numeric constants and methods to help work with numbers.
In JavaScript, primitive numeric values (e.g. 1, 2, 23.12, -2.34) differ from the Number object, their data type is number not object. When you use numbers in JavaScript, you work with primitive numeric values, not instances of the Number object.

The JavaScript interpreter does not use the Number object for implicit data type conversions (when a non-numeric value needs to be converted to numeric, for example 2 * "32"), but the Number object can be used as a function to convert a value to a primitive numeric value explicitly. See Example 3 for details.
When the JavaScript interpreter needs to convert a primitive numeric value to an object, it uses the Number object. Example 5 illustrates this mechanism.

Syntax:

Creating a new Number object:
var num = new Number (number);
Did you find this example helpful? yes no
The type of number can be a number, string or boolean. If number cannot be converted into a numeric value, num will be NaN. In case of string values, leading and trailing whitespaces are allowed. If a string value starts with "0x" or "0X", the base is hexadecimal, otherwise it is decimal. If any part of the string cannot be parsed into a number, the returned value is NaN.
Creating primitive numeric values:

In JavaScript, integers can be represented in decimal, hexadecimal and octal formats, while floating point numbers and numbers in exponential notation must be in decimal format. Hexadecimal integers begin with 0x or 0X followed by one or more hexadecimal digits (0–9, A–F, a-f). Octal integers begin with 0 followed by one or more octal digits (0-7). If an integer begins with 0 and contains the digit 8 or 9, it is a decimal number.
    /*  decimal formats:  */
var num = 12;           // integer
var num = 12.23;        // floating point number
var num = -12.23;       // negative number
var num = .23;          // 0.23
var num = -.23;         // -0.23
var num = 12e3;         // exponential notation (12000)
var num = 12e+3;        // exponential notation (12000)
var num = 12e-3;        // exponential notation (0.012)
var num = 0.012e+3;     // floating point + exponential (12)

    /*  hexadecimal formats:  */
var num = 0xFF;         // value (FF) in hexadecimal format
var num = 0Xaf9857;     // another value (af9857) in hexadecimal format
var num = -0xff;        // negative value (-ff) in hexadecimal format

    /*  not allowed hexadecimal formats:  */
var num = 0xff.12;      // floating point number
var num = 0xffe+3;      // it is allowed, but means 0xffe + 3, not 0xffe * 1000

    /*  octal formats:  */
var num = 0734;         // value (734) in octal format
var num = -023456;      // negative value (-23456) in octal format

    /*  decimal instead of octal  */
var num = 0784;         // value (784) in decimal format since 8 is not an octal digit

    /*  not allowed octal formats:  */
var num = 0734.12;      // floating point number
var num = 0734e+3;      // exponential notation
Did you find this example helpful? yes no
Getting a predefined constant, such as POSITIVE_INFINITY:
var posInf = Number.POSITIVE_INFINITY;
Did you find this example helpful? yes no
Converting values to numeric values:
var num = Number (false);       // 0
var num = Number (true);        // 1 (different from zero)
var num = Number ("10");        // 10
var num = Number ("010");       // 10
var num = Number ("-32");       // -32
var num = Number ("-32.12");    // -32.12
var num = Number ("12e-2");     // 0.12 (exponential notation)
var num = Number ("0x10");      // 16 (hexadecimal base)
var num = Number ("zero");      // NaN

    // date, milliseconds elapsed since 01 January, 1970 00:00:00
var now = new Date ();
var num = now.getTime ();
var num = Number (now);
Did you find this example helpful? yes no
If the value cannot be converted into a numeric value, the returned value is NaN. In case of string values, leading and trailing whitespaces are allowed. If a string value starts with "0x" or "0X", the base is hexadecimal, otherwise it is decimal. Exponential notations are supported for decimal strings. If the whole string cannot be parsed into a number, the returned value is NaN.
Note that the unary addition operator is identical to the Number constructor:
var num = +false;       // 0
var num = +true;        // 1 (different from zero)
var num = +"10";        // 10
var num = +"010";       // 10
var num = +"-32";       // -32
var num = +"-32.12";    // -32.12
var num = +"12e-2";     // 0.12 (exponential notation)
var num = +"0x10";      // 16 (hexadecimal base)
var num = +"zero";      // NaN

    // date, milliseconds elapsed since 01 January, 1970 00:00:00
var now = new Date ();
var num = +now;
Did you find this example helpful? yes no
There are other methods to convert string values to numbers:
  • The parseFloat method converts the specified string to a floating point number. The base is always decimal, but the string may contain additional characters at the end. The parseFloat method converts the longest prefix of the specified string to a floating point number that can be successfully parsed.
  • The parseInt method converts the specified string of the given base to an integer. The string may contain additional characters at the end. The parseInt method converts the longest prefix of the specified string to an integer that can be successfully parsed.
For further details, please see the parseFloat and parseInt methods.
Converting numbers to string literals:
var str = String (56);          // "56"
var str = "" + 56;              // "56"
var str = 56 + "";              // "56"
var str = (56).toString ();     // "56"
var str = (56).toString (2);    // "111000" (binary)
var str = (56).toString (16);   // "38" (hexadecimal)
var str = (56).toString (36);   // "1k" (base of 36)
Did you find this example helpful? yes no
Using methods to add new functionality to the Number object:
function GetDesc () {
    return "number";
}
Number.prototype.description = GetDesc;
Did you find this example helpful? yes no

Members:

The Number object inherits from the Number.prototype and Function.prototype objects. The following lists only contain the members of the Number and Number.prototype objects.

Properties:

Property Support Description
MAX_VALUE
Returns the largest possible number that JavaScript can represent. The MAX_VALUE property is static, it cannot be accessed from an instance of the Number object, only Number.MAX_VALUE is allowed. Be careful, it does not mean that JavaScript can work with numbers between (-1 * Number.MAX_VALUE, Number.MAX_VALUE) correctly. In a 32-bit system the real limit is (-1 * 2^53, 2^53). See the Infinity global property for details and examples.
MIN_VALUE
Returns the smallest positive floating point number, that JavaScript can represent (about 2^-1074). The MIN_VALUE property is static, it cannot be accessed from an instance of the Number object, only Number.MIN_VALUE is allowed.
NaN
Same as the global NaN property. A constant value that indicates that the value of an expression is 'Not-A-Number'. The NaN property is static, it cannot be accessed from an instance of the Number object, only Number.NaN is allowed. If a method (such as parseFloat, parseInt) returns NaN that means that the specified parameter cannot be parsed as a number.
NEGATIVE_INFINITY
Returns negative infinity (any number smaller than MIN_VALUE). Same as the -Infinity global property, see this for details and examples. The NEGATIVE_INFINITY property is static, it cannot be accessed from an instance of the Number object, only Number.NEGATIVE_INFINITY is allowed.
POSITIVE_INFINITY
Returns positive infinity (any number greater than MAX_VALUE). Same as the Infinity global property, see this for details and examples The POSITIVE_INFINITY property is static, it cannot be accessed from an instance of the Number object, only Number.POSITIVE_INFINITY is allowed.
prototype
Returns a reference to the Number.prototype object. The Number.prototype object allows adding properties and methods to the Number object that can be used with instances of the Number object, like any predefined property or method. The prototype property is static, it cannot be accessed from an instance of the Number object, only Number.prototype is allowed.

Methods:

Method Support Description
toExponential ([fractionDigits])*
Returns a string that represents the current number in exponential notation. The string contains one digit before the decimal point and a limited number of digits to the right of the decimal point. At the end of the string a signed integer is displayed after the 'e' letter. This signed integer specifies an exponent of ten indicating the multiplier.
fractionDigits Optional. An integer that specifies the maximum number of digits that can be displayed after the decimal point (from 0 to 20). If not specified, the returned string contains as many digits as can be stored by a floating point number.
toFixed ([fractionDigits])*
Returns a string that represents the current number with a limited number of digits to the right of the decimal point.
fractionDigits Optional. An integer that specifies the maximum number of digits can be displayed after the decimal point (from 0 to 20). Default is 0.
toLocaleString ( )*
Returns a string that represents the current number in a localized form. For example, it may change the decimal point to a comma, because in some languages the numbers are displayed in that form.
toPrecision ([precision])*
Returns a string that represents the current number with the specified number of digits in fixed-point or exponential notation.
precision Optional. Specifies the number of displayed digits. If not specified, the toPrecision method returns the entire number as a string (like toString).
toSource ( )*
Returns a string representing the source code of the current number.
toString ([radix])*
Returns a string that represents the current number in the specified base.
When a number needs to be converted to a string, the JavaScript interpreter automatically calls its toString method.
If you need to convert a string of the given base to an integer, use the parseInt method.
radix Optional. Specifies the binary (2), octal (8), decimal (10), hexadecimal (16) or other (2-36) base. If not specified, the base is decimal (10). The maximum base is 36. The numerals in base of 36 are: 0-9 and a-z.
valueOf ( )*
Returns the current Number object as a primitive numeric value.

(*) - The method is inherited from the Number.prototype.

Examples:

Example 1:

How to get the largest number:
var max = Number.MAX_VALUE;
document.write (max); // output: 1.7976931348623157e+308
Did you find this example helpful? yes no

Example 2:

How to reduce the number of digits after the decimal point:
var num = 123.45678;
document.write (num.toFixed (3)); // output: 123.457
Did you find this example helpful? yes no

Example 3:

Converting values to primitive number values explicitly with the Number function:
var num = Number (false);
document.write (num);           // output: 0
document.write ("<br />");

var num = Number (true);
document.write (num);           // output: 1 (different from zero)
document.write ("<br />");

var num = Number ("10");
document.write (num);           // output: 10
document.write ("<br />");

var num = Number ("010");
document.write (num);           // output: 10
document.write ("<br />");

var num = Number ("-32");
document.write (num);           // output: -32
document.write ("<br />");

var num = Number ("-32.12");
document.write (num);           // output: -32.12
document.write ("<br />");

var num = Number ("12e-2");     // (exponential notation)
document.write (num);           // output: 0.12
document.write ("<br />");

var num = Number ("0x10");      // (hexadecimal base)
document.write (num);           // output: 16
document.write ("<br />");

var num = Number ("zero");
document.write (num);           // output: NaN
document.write ("<br />");
Did you find this example helpful? yes no

Example 4:

Converting floating point values to integers:
<head>
    <script type="text/javascript">
        function Init () {
            var tbody = document.getElementById ("tableBody");
            var values = [6.34, 6.94, -6.34, -6.94];
            for (var i = 0; i < values.length; i++) {
                var row = tbody.insertRow (-1);

                var cell = row.insertCell (-1);
                cell.innerHTML = values[i];
                var cell = row.insertCell (-1);
                cell.innerHTML = Math.round (values[i]);
                var cell = row.insertCell (-1);
                cell.innerHTML = Math.floor (values[i]);
                var cell = row.insertCell (-1);
                cell.innerHTML = Math.ceil (values[i]);
                var cell = row.insertCell (-1);
                cell.innerHTML = ~~values[i];
                var cell = row.insertCell (-1);
                cell.innerHTML = (values[i] ^ 0);
                var cell = row.insertCell (-1);
                cell.innerHTML = (values[i] << 0);
            }
        }
    </script>
</head>
<body onload="Init ()">
    <table border="1px" cellspacing="0" cellpadding="5px">
        <thead>
            <tr>
                <th>x</th>
                <th>Math.round (x)</th>
                <th>Math.floor (x)</th>
                <th>Math.ceil (x)</th>
                <th>~~x</th>
                <th>x ^ 0</th>
                <th>x << 0</th>
            </tr>
        </thead>
        <tbody id="tableBody">
        </tbody>
    </table>
</body>
Did you find this example helpful? yes no

Example 5:

Adding a new method to the Number object and calling it for a primitive numeric value:
Number.prototype.IncreaseByTen = function () {
    return (this + 10);
}

var num = 20;
    // num is a primitive numeric value, not an instance of the Number object,
    // but it will be converted to a Number object before the IncreaseByTen method is called
document.write (num.IncreaseByTen ()); // output: 30

document.write ("<br />");

    // representing the same with an instance of the Number object
var num = new Number (20);
    // num is an instance of the Number object
    // no conversion is needed
document.write (num.IncreaseByTen ()); // output: 30
Did you find this example helpful? yes no

External links:

User Contributed Comments

Post Content

Post Content