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

far out logo

Code Playground

Loading...

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:

far out logo

Code Playground

Loading...
This was pretty far out... now tell me about Binary Search in JavaScript
Far Out Logo
That was pretty far out... but I want to learn about How to use the React useCallback() hook