Converting a string to a number in JavaScript

Published Oct 10 2022

The most commonly used method of converting a number to a string in JavaScript is the parseInt() function. It takes two arguments a string and a radix

and parses the string to return the an integer of the specified radix. When a radix argument is not provided, the conversion is done in base 10 (decimal). In case the first non-whitespace character of the string is not a number then parseFloat() returns NaN (Not a Number).

An alternative way of performing this explicit type conversion is to use the global Number() constructor function. This method has a small performance advantage* over the parseInt(). Number() 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.

Number() and parseInt() examples

far out logo

Code Playground

Loading...

Using parseFloat()

You may have noticed that one limitation of using parseInt() or Number() is that they return whole integers, stripping any decimals. If instead we want to return a floating point number, we can instead use parseFloat(). parseFloat() takes a string argument and returns a floating point number. It can be combined with the toFixed () method on the Number class to return a floating point number with the the specified number of decimal places:

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