3 Ways to Convert Strings to Numbers in JavaScript
Let's look at 3 techniques that you can use to convert strings into numbers in JavaScript. Each method has its own strengths and weaknesses, so choose the one that best fits your specific use case.
Let's dive in!
1. Number()
Object
In my opinion, this is the best method to use. It takes care of point numbers as well.
Number("12") //12 Number("13.91") //13.91
However, if the string contains non-numeric characters, such as separators, it will return NaN
(Not a Number).
Number("10,000") //NaN
So, if you want to safely fail back to NaN for a bad input, Number()
is a good choice.
2. ParseInt()
and ParseFloat()
Method
You can also use the parseInt()
and parseFloat()
methods to convert strings to numbers.
The parseInt()
method takes two arguments - the string and a radix. Radix is a number which represents the base in the number system. For our case, it should be 10.
Remember to not forget passing the second parameter. If the radix parameter is not provided, the conversion will try to guess the radix, which can result in unexpected and unreliable results.
parseInt("17", 10) //returns 17 parseInt("12.14", 10) //returns 12
Be aware that parseInt()
will silently stop parsing if it encounters non-numeric characters. This can be useful for parsing strings like "92px", but it can also be dangerous since it won't give you an error for bad input.
parseInt("97,800", 10) //97 parseInt("10 lions", 10) //10
You'll get back NaN
if the string starts with a non-numeric character.
parseInt("I'm 10", 10) //NaN
If you want to retain the decimal part and not just get the integer part, use parseFloat()
. Unlike its parseInt()
sibling, it only takes one argument - the string to convert.
parseFloat("12.99") // 12.99 parseFloat("10000") // 10000 parseFloat("10,000") // 10
3. Implicit Coercing to Number
All of the methods below implicitly coerce the type from string to a number, which is the same thing that we do explicitly with the Number()
object.
Unary Plus
You can convert a string to a number by placing the plus sign in front of the string.
+"1000" //1000
Math.floor()
The Math.floor()
method first implicitly converts the string to a number and then rounds it down to the nearest integer.
Math.floor("1000.01") // 1000
Math.round()
The Math.round()
method also first implicitly converts the string to a number and then rounds it to the nearest integer.
Math.round("1000") //1000
Get my free, weekly JavaScript tutorials
Want to improve your JavaScript fluency?
Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.
Join today, and level up your JavaScript every Sunday!
Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.