All JavaScript numbers can utilize these number methods.
Method |
Description |
toString() |
Converts a number into a string. |
toExponential() |
Converts a number written in exponential notation |
toFixed() |
Converts a number written with a number of decimals |
toPrecision() |
Converts a number written with a specified length |
valueOf() |
Converts a number as a number |
The toString() method converts a number into a string, and all number methods are applicable to any form of numbers, including literals, variables, or expressions.
Example
let x = 123; x.toString(); (123).toString(); (100 + 23).toString(); |
The toExponential() method converts a number into a string representation using exponential notation, with an optional parameter specifying the number of digits after the decimal point.
Example
let x = 9.656; x.toExponential(2); x.toExponential(4); x.toExponential(6); |
The parameter for the toExponential() method is optional; if omitted, JavaScript will not round the number.
The toFixed() method returns a string representation of a number with a specified fixed number of decimal places.
Example
let x = 9.656; x.toFixed(0); x.toFixed(2); x.toFixed(4); x.toFixed(6); |
Using toFixed(2) is ideal for handling monetary values.
The toPrecision() method returns a string representation of a number with a specified total length.
Example
let x = 9.656; x.toPrecision(); x.toPrecision(2); x.toPrecision(4); x.toPrecision(6); |
The valueOf() method returns the primitive value of a number as a number type.
Example
let x = 123; x.valueOf(); (123).valueOf(); (100 + 23).valueOf(); |
In JavaScript, a number can exist either as a primitive value (typeof = number) or as an object (typeof = object).
The valueOf() method is internally employed by JavaScript to convert Number objects into primitive values.
Typically, there’s no necessity to explicitly use it in your code.
Every JavaScript data type is equipped with both a valueOf() and a toString() method. |
Three methods in JavaScript are available for converting a variable into a number.
Method |
Description |
Number() |
Returns a number obtained by converting its argument. |
parseFloat() |
Parses its argument and returns a floating-point number. |
parseInt() |
Parses its argument and returns an integer. |
The aforementioned methods are not specific to numbers but are global methods available in JavaScript. |