Loading
Number in Javascript-tutorial
In JavaScript, numbers can be stored as primitive values (like 10 or 102.7) or as objects using the Number object.
The Number object helps represent numeric values, whether integers, floating-point numbers, or values in exponent notation.



How to Create Number Objects

You can crate number objects in two ways


Using Number constructor

var n = new Number(10);


Directly assign numbers to variables

var x = 102;          // integer
var y = 102.7;        // floating-point number
var z = 13e4;         // exponent notation, equals 130000



Example:

<!DOCTYPE html>
<html>

<body>
    <script>
        var x = 102;                // integer value  
        var y = 102.7;              // floating point value  
        var z = 13e4;               // exponent value (130000)  
        var n = new Number(10);     // number object  
        document.write(x + " " + y + " " + z + " " + n);
    </script>
</body>

</html>

Output

Uploaded Image




Number Constants

JavaScript also provides predefined number constants like

  • Number.MAX_VALUE – Largest representable number
  • Number.MIN_VALUE – Smallest positive number
  • Number.POSITIVE_INFINITY – Infinity
  • Number.NEGATIVE_INFINITY – -Infinity
  • Number.NaN – Not a Number



Number Methods

Numbers in JavaScript can use methods (thanks to auto-boxing, where primitive numbers are temporarily wrapped as Number objects).



Example:

let num = 3.14159;

let str = num.toString();    // Convert number to string
console.log(str);            // Output: "3.14159"

let fixed = num.toFixed(2);  // Round to two decimal places
console.log(fixed);          // Output: "3.14"



Key Point

  • JavaScript automatically handles numbers as primitive values or objects when needed.
  • Number objects are rarely used, but methods like toString(), toFixed(), and toPrecision() are very useful.
  • Supports integers, floating points, and exponent notation.