Convert string to number with JavaScript

Been working through swapping a MySQL library recently to prepare for a major database upgrade. The old library would return the results from function like AVG and SUM as a number. The new library, not so much.

MySQL natively returns those values as strings, which I can applaud the library for respecting. Coming from a library that was doing the conversion automatically left us with a ton of broken tests and code to patch.

Fortunately, it’s not that hard to convert a string to a number. There’s also multiple ways to approach the problem, based on what type of number you’re expecting to get back.

String to integer

If you are expecting a string to be an integer, you can use the parseInt function, explicitly letting it know the base you’re working with:

> parseInt('12345', 10);

12345
JavaScript

If you were to pass in a number with a decimal, the function will still work, but it will strip everything after the decimal point. No rounding occurs either:

> parseInt('12345.67', 10);

12345
JavaScript

String to decimal

If you are working with numbers with decimals you can use the Number constructor:

> Number(12345.67);

12345.67
JavaScript

This also works with integers, so this tends to be my preferred method to convert strings to numbers:

> Number('12345');

12345
JavaScript
Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.