JavaScript Number Methods
•JavaScript•1 min read

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 number123.456789to 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,
xis a number (123). - The
toString()method convertsxinto a string and assigns it toy. - The type of
yis now"string".
3. isNaN() Method
- The
isNaN()method checks if a value is "Not-a-Number" (NaN) and returnstrueif the value is not a number, otherwise it returnsfalse. - 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 because45is a valid number.isNaN("hello")returnstruebecause"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".



