JavaScript : Number Methods

In JavaScript, the Number object provides a variety of methods for working with numbers. These methods are static, meaning they are called directly on the Number object itself, rather than on instances of the object. Here are some commonly used number methods in JavaScript:

1. Number.isNaN()


Checks whether a value is NaN (Not a Number).


Number.isNaN(NaN);        // true
Number.isNaN("Hello");    // false

 

2. Number.isFinite()


Checks whether a value is a finite number.


Number.isFinite(10);      // true
Number.isFinite(Infinity); // false

 

3. Number.isInteger()


Checks whether a value is an integer.


Number.isInteger(10);     // true
Number.isInteger(10.5);   // false

 

4. Number.parseFloat()


Parses a string and returns a floating-point number.


Number.parseFloat("3.14");   // 3.14
Number.parseFloat("10px");   // 10

 

5. Number.parseInt()


Parses a string and returns an integer.


Number.parseInt("10");     // 10
Number.parseInt("10.5");   // 10

 

6. Number.toFixed()


Formats a number using fixed-point notation with a specified number of digits after the decimal point.


let num = 3.14159;
num.toFixed(2);   // "3.14"

 

7. Number.toPrecision()


Formats a number using exponential (scientific) notation with a specified number of significant digits.


let num = 123.456;
num.toPrecision(2);   // "1.2e+2"

 

8. Number.toString()


Converts a number to a string.


let num = 123;
num.toString();   // "123"

 

9. Number.MAX_VALUE` and `Number.MIN_VALUE


Returns the maximum and minimum representable numbers in JavaScript.


console.log(Number.MAX_VALUE);   // 1.7976931348623157e+308
console.log(Number.MIN_VALUE);   // 5e-324

 

10. Number.NaN, Number.POSITIVE_INFINITY, and Number.NEGATIVE_INFINITY


Constants representing NaN, positive infinity, and negative infinity, respectively.


console.log(Number.NaN);                // NaN
console.log(Number.POSITIVE_INFINITY);  // Infinity
console.log(Number.NEGATIVE_INFINITY);  // -Infinity

 

These are some of the methods and constants provided by the Number object in JavaScript. They are useful for various numerical operations and conversions in your JavaScript code.