How to convert a string to a number in JavaScript

Converting strings to numbers is essential for form data processing, mathematical calculations, API data handling, and implementing features like calculators or numeric validation in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented string-to-number conversion extensively in components like input fields, calculators, and data processors where reliable numeric conversion ensures proper mathematical operations and data integrity. From my extensive expertise, the most robust and recommended approach is using the Number() constructor, which provides consistent conversion behavior and clear error handling. This method is explicit, handles various string formats, and produces predictable results across different scenarios.

Use the Number() constructor to convert a string to a number.

const stringValue = '42'
const numberValue = Number(stringValue)
// Result: 42

const floatValue = Number('3.14')
// Result: 3.14

The Number() constructor converts the entire string to a number, returning NaN if the conversion fails. In these examples, Number('42') returns the integer 42, and Number('3.14') returns the float 3.14. This method handles integers, decimals, and scientific notation properly. If the string contains non-numeric characters (except leading/trailing whitespace), it returns NaN. Empty strings convert to 0, and strings with only whitespace also convert to 0.

Best Practice Note:

This is the same approach we use in CoreUI components for processing form inputs, handling API responses, and performing calculations across our component ecosystem. Alternative methods include the unary plus +stringValue for conciseness, parseInt() for integers only, and parseFloat() for decimals. Always validate the result with isNaN() or Number.isNaN() when user input is involved. The Number() method is preferred for its explicit intent and consistent behavior with different value types.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author