Converting a number to a string in JavaScript
Published Jul 20 2022
The most commonly used method of converting a number to a string in JavaScript is the toString() method. This method is defined on the Number object and takes a radix (or base) as an optional argument. When the radix is not specified the conversion is done in base 10 (decimal).
An alternative way of performing this explicit type conversion is to use the global String() constructor function. String() also defaults to converting using a base of 10. We can see in the code playground that the output of these two options is identical.
String() and toString() examples
Code Playground
toFixed(), toExponential() and toPrecision()
Three more methods exist on the Number object for converting a number to a string. These provide more control over the format of the returned string. The toFixed() method takes an optional digits argument and formats the number using fixed-point notation. This can be useful when displaying currency in the UI.
toExponential() returns a string in exponential notation while toPrecision() returns a string of a specified length. These three alternative methods are best understood by example: