JavaScript Number Methods
JavaScript Number Methods
Section titled “JavaScript Number Methods”JavaScript provides several built-in methods to work with numbers, for formatting, conversion, and other operations.
Global Functions for Numbers
Section titled “Global Functions for Numbers”JavaScript has global functions that are commonly used with numbers, although they can operate on other data types for conversion purposes.
The most relevant global functions for numeric operations are:
| Method | Description |
|---|---|
| Number(value) | Converts its argument to a number. Returns NaN if conversion is not possible. |
| parseFloat(string) | Parses its string argument and returns a floating-point number. Stops parsing at the first non-numeric character. |
| parseInt(string, radix) | Parses its string argument and returns an integer of the specified radix (base). Always specify the radix (e.g., 10 for decimal). |
Number Prototype Methods
Section titled “Number Prototype Methods”These methods are called on number values themselves (primitives or Number objects). JavaScript automatically wraps number primitives with a Number object to access these methods (auto-boxing).
| Method | Description |
|---|---|
| toString(radix) | Returns a string representation of the number. An optional radix (2-36) can specify the base for conversion (e.g., 2 for binary, 16 for hexadecimal). Defaults to base 10. |
| toExponential(fractionDigits) | Returns a string representing the number in exponential notation. fractionDigits (0-100) specifies the number of digits after the decimal point. |
| toFixed(digits) | Returns a string representing the number in fixed-point notation. digits (0-100) specifies the number of digits to appear after the decimal point; the number is rounded if necessary. |
| toPrecision(precision) | Returns a string representing the number to a specified precision (total number of significant digits, 1-100). |
| valueOf() | Returns the primitive value of a Number object. Called internally by JavaScript; rarely used directly in code. |
| Important Note: | All number methods return a new value (usually a string, except valueOf). They do not modify the original number variable. |
|---|
The toString() Method
Section titled “The toString() Method”toString() converts a number to its string representation.
It can be used on number literals, variables, or expressions. An optional radix argument specifies the base.
const num = 123;num.toString(); // "123" (base 10 by default)(42).toString(); // "42"(100 + 23).toString(); // "123"
num.toString(2); // "1111011" (binary)num.toString(16); // "7b" (hexadecimal)The toExponential() Method
Section titled “The toExponential() Method”toExponential() returns a string representing the number in exponential (scientific) notation.
An optional parameter fractionDigits specifies the number of digits after the decimal point.
const x = 9.656;x.toExponential(2); // "9.66e+0"x.toExponential(4); // "9.6560e+0"x.toExponential(); // "9.656e+0" (if no argument, includes as many digits as necessary)
const largeNum = 12345e8;largeNum.toExponential(3); // "1.235e+12"The toFixed() Method
Section titled “The toFixed() Method”toFixed() formats a number using fixed-point notation and returns a string.
It takes an argument digits indicating the number of decimal places. The number is rounded if necessary.
const x = 9.656;x.toFixed(0); // "10" (rounds up)x.toFixed(2); // "9.66" (rounds up)x.toFixed(4); // "9.6560"x.toFixed(6); // "9.656000"
const y = 123.456;(2.34).toFixed(1); // "2.3"(2.35).toFixed(1); // "2.4" (note rounding)| Tip: | toFixed(2) is commonly used for formatting currency values. |
|---|
The toPrecision() Method
Section titled “The toPrecision() Method”toPrecision() returns a string representing the number to a specified number of significant digits.
If the precision is less than the number of digits in the integer part, exponential notation is used.
const x = 9.656;x.toPrecision(); // "9.656" (full precision)x.toPrecision(2); // "9.7" (rounded to 2 significant digits)x.toPrecision(4); // "9.656"x.toPrecision(6); // "9.65600"
const y = 1234.5;y.toPrecision(2); // "1.2e+3" (exponential notation)y.toPrecision(7); // "1234.500"Converting Values to Numbers (Recap)
Section titled “Converting Values to Numbers (Recap)”As mentioned, there are 3 global JavaScript functions useful for converting various types to numbers:
Number(value): The most direct way to convert something to a number.parseInt(string, radix): For converting strings to integers.parseFloat(string): For converting strings to floating-point numbers.
These are global functions, not methods of number objects.
The Number() Function
Section titled “The Number() Function”Number() attempts to convert its argument into a numerical value.
Number(true); // 1Number(false); // 0Number(null); // 0Number(undefined); // NaNNumber(new Date()); // Milliseconds since Jan 1, 1970 UTC (e.g., 1678886400000)Number("10"); // 10Number(" 10 "); // 10 (whitespace trimmed)Number("10.33"); // 10.33Number("10,33"); // NaN (comma is not a decimal point in this context)Number("10 20"); // NaN (space makes it invalid for Number())Number("John"); // NaNThe parseInt() Function
Section titled “The parseInt() Function”parseInt() parses a string argument and returns an integer. It’s crucial to provide the radix (base) argument to avoid unexpected behavior, especially with strings that might start with ‘0’ or ‘0x’.
parseInt("10", 10); // 10parseInt("10.33", 10); // 10 (stops at decimal point)parseInt("10 20 30", 10); // 10 (stops at space)parseInt("10 years", 10); // 10 (stops at 'y')parseInt("years 10", 10); // NaN (doesn't start with a number)parseInt("010", 10); // 10 (radix 10 ensures decimal interpretation)parseInt("010"); // In older JS, might be 8 (octal). Modern JS defaults to 10 if no '0x' prefix. // ALWAYS use radix: parseInt("010", 10) is safe.parseInt("FF", 16); // 255 (hexadecimal)If the first character cannot be converted to a number, parseInt() returns NaN.
The parseFloat() Function
Section titled “The parseFloat() Function”parseFloat() parses a string argument and returns a floating-point number. It continues parsing until it encounters a character that isn’t part of a valid number representation.
parseFloat("10"); // 10parseFloat("10.33"); // 10.33parseFloat("10.00"); // 10parseFloat("10 20 30"); // 10 (stops at space)parseFloat("10 years"); // 10 (stops at 'y')parseFloat("years 10"); // NaN (doesn't start with a number)parseFloat("3.14e2"); // 314parseFloat(" -2.5 "); // -2.5 (handles leading/trailing whitespace and sign)If the first character cannot be converted to a number, parseFloat() returns NaN.
The valueOf() Method
Section titled “The valueOf() Method”valueOf() returns the primitive value of a Number object. This method is usually called internally by JavaScript and is not typically used explicitly in your code.
const numObj = new Number(123);numObj.valueOf(); // 123 (the primitive number)
const primitiveNum = 42;primitiveNum.valueOf(); // 42 (returns the primitive itself)In JavaScript, a number can be a primitive value (typeof num === 'number') or an object created with new Number() (typeof numObj === 'object'). Working with primitive numbers is almost always preferred for performance and simplicity.
| Note: | All primitive data types in JavaScript (except null and undefined) have a valueOf() method. Objects also have valueOf() and toString() methods, often overridden for custom behavior. |
|---|
Consider BigInt for numbers exceeding Number.MAX_SAFE_INTEGER or requiring arbitrary precision integer arithmetic. BigInt has its own set of operations and is not compatible with Number methods directly.
Further reading: MDN: Number, MDN: parseInt