JavaScript Number Methods
Subject: JavaScript
JavaScript provides several built-in Number methods to format, convert, and perform utility operations on numeric values. These methods are useful for calculations, currency formatting, and controlling numeric precision.
What Are Number Methods?
Number methods are functions called on Number objects or numeric values to manipulate or retrieve number-related information. Most return strings rather than numbers.
Common Number Methods
- toString() Converts a number to a string.
You can specify a base (radix):
- toFixed(digits) Formats the number with a fixed number of decimal places.
Commonly used for currency formatting.
- toExponential(fractionDigits) Returns a string in exponential notation.
- toPrecision(totalDigits) Returns a string representing the number to a specified length.
- valueOf() Returns the primitive value of a Number object.
Useful when working with Number objects rather than literals.
- Number.isInteger(value) Checks if a value is an integer.
- Number.isFinite(value) Determines if the value is a finite number.
- Number.isNaN(value) Checks if the value is NaN (Not a Number).
- parseInt() and parseFloat() Convert strings to numbers.
- Number() Converts various types to numbers.
Key Takeaways
- Use toFixed() and toPrecision() to control decimal formatting.
- toExponential() is useful for large scientific numbers.
- Use Number.isFinite(), Number.isNaN(), and Number.isInteger() for validation.
- Convert values with Number(), parseInt(), or parseFloat() depending on the context.