JavaScript Number Methods

JavaScript1 min read
JavaScript Number Methods
javascriptnumber method

In JavaScript, several methods are available to perform operations on numbers. Let's explore some of the most commonly used number methods.

In JavaScript, several methods are available to perform operations on numbers. Let's explore some of the most commonly used number methods:

1. toFixed() Method

  • The toFixed() method formats a number to a specified number of decimal places and returns it as a string.

  • Example:

let num = 123.456789; // Format the number to 2 decimal places document.write(num.toFixed(2)); // Output: "123.46"

Explanation:

  • The toFixed(2) method formats the number 123.456789 to two decimal places, rounding it to "123.46".
  • It returns the result as a string.

2. toString() Method

  • The toString() method converts a number to a string.
  • Example:
let x = 123; // Check the type of x document.write(typeof x); // Output: "number" // Convert x to a string let y = x.toString(); // Check the type of y document.write(typeof y); // Output: "string"

Explanation:

  • Initially, x is a number (123).
  • The toString() method converts x into a string and assigns it to y.
  • The type of y is now "string".

3. isNaN() Method

  • The isNaN() method checks if a value is "Not-a-Number" (NaN) and returns true if the value is not a number, otherwise it returns false.
  • Example:
// Check if 45 is NaN document.write(isNaN(45)); // Output: "false" // Check if a string is NaN document.write(isNaN("hello")); // Output: "true"

Explanation:

  • isNaN(45) returns false because 45 is a valid number.
  • isNaN("hello") returns true because "hello" is not a number.

Summary:

  • toFixed() formats a number to a specific number of decimal places.
  • toString() converts a number to a string.
  • isNaN() checks if a value is "Not-a-Number".