The JavaScript Number object is used to represent numeric values. It can handle both integer and floating-point numbers and follows the IEEE standard for representing floating-point numbers.
You can create a Number object using the Number() constructor. Additionally, you can directly assign a number to a variable.
var n = new Number(123);
var n = 123;
If the value cannot be converted to a number, it returns NaN (Not a Number), which can be checked using the isNaN() method.
| Property | Description |
|---|---|
| Number.MAX_VALUE | The largest possible number in JavaScript. |
| Number.MIN_VALUE | The smallest possible number in JavaScript. |
| Number.POSITIVE_INFINITY | Represents positive infinity. |
| Number.NEGATIVE_INFINITY | Represents negative infinity. |
| Number.NaN | Represents Not-a-Number. |
| Method | Description |
|---|---|
| toString() | Returns the string representation of the number. |
| toFixed(digits) | Formats the number using fixed-point notation. |
| toExponential(digits) | Formats the number using exponential notation. |
| toPrecision(digits) | Formats the number to a specified length. |
| valueOf() | Returns the primitive value of the number. |
| isNaN(value) | Checks if the value is NaN. |
| isFinite(value) | Checks if the value is a finite number. |
| parseFloat(string) | Parses a string and returns a floating-point number. |
| parseInt(string, radix) | Parses a string and returns an integer of the specified radix (base). |
Here's an example HTML file demonstrating some of the properties and methods of the Number object:
<script>
var n = 123.456;
var nObj = new Number(123.456);
document.write("Number: " + n );
document.write("Number Object: " + nObj );
document.write("MAX_VALUE: " + Number.MAX_VALUE );
document.write("MIN_VALUE: " + Number.MIN_VALUE );
document.write("POSITIVE_INFINITY: " + Number.POSITIVE_INFINITY );
document.write("NEGATIVE_INFINITY: " + Number.NEGATIVE_INFINITY);
document.write("NaN: " + Number.NaN );
document.write("toString(): " + n.toString() );
document.write("toFixed(2): " + n.toFixed(2) );
document.write("toExponential(2): " + n.toExponential(2) );
document.write("toPrecision(4): " + n.toPrecision(4) );
document.write("valueOf(): " + nObj.valueOf() );
document.write("isNaN('abc'): " + isNaN('abc') );
document.write("isFinite(123): " + isFinite(123) );
document.write("parseFloat('123.456'): " + parseFloat('123.456') );
document.write("parseInt('123.456', 10): " + parseInt('123.456', 10) );
<script>
Number: 123.456
Number Object: 123.456
MAX_VALUE: 1.7976931348623157e+308
MIN_VALUE: 5e-324
POSITIVE_INFINITY: Infinity
NEGATIVE_INFINITY: -Infinity
NaN: NaN
toString(): 123.456
toFixed(2): 123.46
toExponential(2): 1.23e+2
toPrecision(4): 123.5
valueOf(): 123.456
isNaN('abc'): true
isFinite(123): true
parseFloat('123.456'): 123.456
parseInt('123.456', 10): 123