Number Methods

JavaScript provides several built-in methods to work with Number values. These methods help you format, convert, and manipulate numbers efficiently.

Common Number Methods

  • toFixed(digits): Formats a number using fixed-point notation, rounding to the specified number of decimal places.
  • toPrecision(precision): Formats a number to a specified total number of significant digits.
  • toString([radix]): Converts a number to a string, optionally using a specified base (radix) between 2 and 36.
  • Number.isInteger(value): Checks if the given value is an integer.
  • Number.isNaN(value): Checks if a value is the special NaN (Not-a-Number) value.
Number Method Summary
MethodDescription
toFixed(digits)Rounds and formats number to fixed decimal places
toPrecision(precision)Formats number to specified significant digits
toString([radix])Converts number to string, optionally in specified base
Number.isInteger(value)Returns true if value is an integer
Number.isNaN(value)Returns true if value is NaN

📌 Deep Dive: Using toFixed() and toPrecision()

JAVASCRIPT
const num = 123.456789;

console.log(num.toFixed(2));      // "123.46" - rounded to 2 decimal places
console.log(num.toFixed(0));      // "123" - rounded to nearest integer

console.log(num.toPrecision(4));  // "123.5" - 4 significant digits
console.log(num.toPrecision(6));  // "123.457" - 6 significant digits
Output
"123.46"
"123"
"123.5"
"123.457"

📌 Deep Dive: Converting Numbers to Strings with toString()

JAVASCRIPT
const num = 255;

console.log(num.toString());     // "255" (default base 10)
console.log(num.toString(2));    // "11111111" (binary)
console.log(num.toString(16));   // "ff" (hexadecimal)
Output
"255"
"11111111"
"ff"
Illustration of number_methods
Illustration of number_methods

💡 Note on Number.isNaN() vs global isNaN()

Number.isNaN() only returns true for actual NaN values, while the global isNaN() converts the argument to a number first and can give unexpected results.

📌 Deep Dive: Checking Integers and NaN

JAVASCRIPT
console.log(Number.isInteger(25));        // true
console.log(Number.isInteger(25.1));      // false

console.log(Number.isNaN(NaN));           // true
console.log(Number.isNaN("hello"));       // false
console.log(isNaN("hello"));               // true (global isNaN coerces)
Output
true
false
true
false
true

⚠️ Beware of toFixed() returning strings

Note that toFixed() returns a string, not a number. Use parseFloat() if you need a number.

📌 Deep Dive: Getting a Number from toFixed()

JAVASCRIPT
const num = 3.14159;
const fixedString = num.toFixed(2);   // "3.14"
const fixedNumber = parseFloat(fixedString);

console.log(typeof fixedString);      // "string"
console.log(typeof fixedNumber);      // "number"
Output
"string"
"number"

💡 Summary

Number methods help you format and validate numbers with ease. Remember to check return types and use the appropriate method for your needs.