Flat Preloader Icon

JS Number

The Number object in JavaScript is a global object and constructor function that represents numerical values. It provides properties and methods for working with numbers in JavaScript.

1. Creating Number Objects:

  • You can create a Number object using the Number() constructor:
				
					const num = new Number(42);

				
			

However, it’s more common to use primitive number literals:

				
					const num = 42;

				
			

2. Properties of Number Object:

  • Number.MAX_VALUE: Returns the largest representable number in JavaScript.
  • Number.MIN_VALUE: Returns the smallest positive representable number in JavaScript.
  • Number.NaN: Represents “Not-A-Number” value.
  • Number.NEGATIVE_INFINITY: Represents negative infinity.
  • Number.POSITIVE_INFINITY: Represents positive infinity.

3. Methods of Number Object:

  • .toString(): Converts a number to a string.
  • .toFixed(): Formats a number using fixed-point notation.
  • .toPrecision(): Formats a number to a specified precision in scientific notation.
  • .valueOf(): Returns the primitive value of a Number object.
  • .parseInt(): Parses a string and returns an integer.
  • .parseFloat(): Parses a string and returns a floating-point number.
				
					const num = 42.555;
console.log(num.toFixed(2)); 
// Outputs: 42.56
console.log(num.toPrecision(3)); 
// Outputs: 42.6e+0
console.log(num.toString()); 
// Outputs: "42.555"
console.log(num.valueOf()); 
// Outputs: 42.555
console.log(Number.parseInt("10")); 
// Outputs: 10
console.log(Number.parseFloat("3.14"));
// Outputs: 3.14

				
			

Static Methods of Number Object:

  • Number.isFinite(): Checks whether a value is a finite number.
  • Number.isInteger(): Checks whether a value is an integer.
  • Number.isNaN(): Checks whether a value is NaN.
  • Number.isSafeInteger(): Checks whether a value is a safe integer.
				
					console.log(Number.isFinite(42));
// Outputs: true
console.log(Number.isInteger(42));
// Outputs: true
console.log(Number.isNaN(42));
// Outputs: false
console.log(Number.isSafeInteger(42)); 
// Outputs: true