JavaScript provides several methods for working with numbers. These methods allow you to manipulate, format, and check numbers in various ways. Here, we'll explore these methods with explanations and examples, including any optional parameters they may accept.
Converts a number to its string representation.
let num = 42;
let numString = num.toString(); // "42" (a string)
console.log(numString) // "42" (a string)
This method doesn't accept any parameters.
Formats a number with a fixed number of decimal places and returns a string representation.
let num = 42.34567;
let fixedNum = num.toFixed(2); // "42.35" (a string with 2 decimal places)
console.log(fixedNum) // "42.35" (a string with 2 decimal places)
Formats a number with a specified precision (total number of significant digits) and returns a string representation.
let num = 42.34567;
let preciseNum = num.toPrecision(4); // "42.35" (a string with 4 significant digits)
console.log(preciseNum) // "42.35" (a string with 4 significant digits)
Parses a string and returns an integer. It stops parsing when a non-numeric character is encountered.
let str = "42px";
let parsedInt = parseInt(str); // 42 (an integer)
console.log(parsedInt) // 42 (an integer)
Parses a string and returns a floating-point number. It stops parsing when a non-numeric character is encountered.
let str = "42.34567";
let parsedFloat = parseFloat(str); // 42.34567 (a floating-point number)
console.log(parsedFloat) // 42.34567 (a floating-point number)
Checks if a value is NaN (Not-a-Number).
let notANumber = NaN;
let isItNaN = isNaN(notANumber); // true
console.log(isItNaN) // true
Checks if a value is a finite number (not NaN, Infinity, or -Infinity).
let finiteNumber = 42;
let isItFinite = isFinite(finiteNumber); // true
console.log(isItFinite) // true
A more robust version of isNaN(). It returns true only if the provided value is exactly NaN.
let notANumber = NaN;
let isItNaN = Number.isNaN(notANumber); // true
console.log(isItNaN) // true
Checks if a value is an integer.
let integer = 42;
let isItInteger = Number.isInteger(integer); // true
console.log(isItInteger) // true
Understanding these methods and their optional parameters allows you to perform various operations on numbers effectively in JavaScript, including parsing, formatting, and checking for special values.