Mapagam
  • JavaScript 
  • Web APIs 
  • TypeScript 
  • React 

How to Convert Strings to Numbers in JavaScript (And Vice Versa!)

Posted on April 8, 2025 • 6 min read • 1,243 words
Share via
Mapagam
Link copied to clipboard

Learn how to convert strings to numbers and numbers to strings in JavaScript with various methods and best practices for efficient coding.

On this page
1. Introduction to Data Type Conversion in JavaScript 2. Converting Strings to Numbers in JavaScript 2.1. Using Number() 2.2. Using parseInt() 2.3. Using parseFloat() 2.4. Using the Unary Plus (+) Operator 2.5. Implicit Type Conversion (Type Coercion) 3. Converting Numbers to Strings in JavaScript 3.1. Using String() 3.2. Using toString() 3.3. Using String Concatenation 3.4. Using Template Literals 4. Special Cases in Type Conversion 4.1. Empty String Conversion 4.2. NaN (Not-a-Number) 5. Best Practices for Type Conversion in JavaScript 5.1. Validate User Input 5.2. Handle NaN Carefully 5.3. Use the Right Method for the Job 6. Conclusion

JavaScript is one of the most commonly used languages in modern web development, offering powerful tools for manipulating data. One of the most frequent tasks in JavaScript programming is converting between different data types—specifically, converting strings to numbers and vice versa. This is essential when performing mathematical operations or working with user inputs, which are often captured as strings.

1. Introduction to Data Type Conversion in JavaScript

JavaScript is a loosely typed language, which means it doesn’t require variables to have a specified data type. Variables can hold values of any type, and JavaScript will attempt to automatically convert between data types when necessary. However, developers often need to explicitly convert between strings and numbers to ensure accurate operations.

In JavaScript, numbers and strings are two of the most common data types, and developers need to know how to convert between the two effectively. Whether you’re working with user inputs, parsing data from external sources, or performing calculations, understanding the nuances of type conversion is crucial for writing efficient and error-free code.

2. Converting Strings to Numbers in JavaScript

In JavaScript, a string containing numerical characters can be converted into a number using several methods. Below, we will explore the most popular ways to perform this conversion.

2.1. Using Number()

The Number() function is one of the most straightforward ways to convert a string to a number in JavaScript. This function attempts to convert the input value into a number.

Example:

let str = "123";
let num = Number(str);
console.log(num); // 123
console.log(typeof num); // number

In the example above, the string "123" is successfully converted into the number 123.

However, if the string cannot be converted into a valid number, Number() will return NaN (Not-a-Number).

Example of invalid conversion:

let str = "Hello";
let num = Number(str);
console.log(num); // NaN
console.log(typeof num); // number

2.2. Using parseInt()

The parseInt() function parses a string and returns an integer value. If the string contains non-numeric characters, it will convert the string until it reaches the first invalid character.

Example:

let str = "123abc";
let num = parseInt(str);
console.log(num); // 123

In this example, parseInt() successfully converts the string "123abc" into the integer 123. If the string starts with a non-numeric character, parseInt() will return NaN.

2.3. Using parseFloat()

The parseFloat() function works similarly to parseInt(), but it converts the string into a floating-point number instead of an integer. This method is ideal when you need to handle decimal values.

Example:

let str = "123.45";
let num = parseFloat(str);
console.log(num); // 123.45

If the string represents a number with a decimal, parseFloat() will preserve that part of the value. If the string contains invalid characters after a valid number, parseFloat() will parse the string until it encounters the invalid character.

2.4. Using the Unary Plus (+) Operator

A shorthand method for converting a string to a number in JavaScript is by using the unary plus (+) operator. This operator is a concise way to force JavaScript to attempt to convert a string into a number.

Example:

let str = "123";
let num = +str;
console.log(num); // 123

The unary plus operator is not only compact but also one of the most commonly used methods for simple conversions.

2.5. Implicit Type Conversion (Type Coercion)

JavaScript is known for its implicit type conversion or type coercion. If you attempt to perform an operation that requires a number, such as arithmetic, JavaScript will attempt to convert the string into a number automatically.

Example:

let str = "10";
let num = str * 2; // JavaScript automatically converts the string to a number
console.log(num); // 20

In this example, JavaScript automatically converts the string "10" into the number 10 during the multiplication operation, producing the result 20.

3. Converting Numbers to Strings in JavaScript

In many scenarios, you may need to convert numbers to strings. Fortunately, JavaScript offers several ways to achieve this.

3.1. Using String()

The String() function is one of the easiest ways to convert a number to a string. It can be used to convert both numbers and other data types to strings.

Example:

let num = 123;
let str = String(num);
console.log(str); // "123"
console.log(typeof str); // string

3.2. Using toString()

Each number in JavaScript has a built-in method called toString() that can be called to convert the number into a string.

Example:

let num = 456;
let str = num.toString();
console.log(str); // "456"
console.log(typeof str); // string

This method works similarly to String() but is specifically tied to the Number object, and it’s a common approach to convert numbers to strings.

3.3. Using String Concatenation

Another way to convert a number into a string is by concatenating it with an empty string (""). JavaScript will automatically convert the number into a string during this operation.

Example:

let num = 789;
let str = num + "";
console.log(str); // "789"
console.log(typeof str); // string

This method works because the + operator in JavaScript, when used with a string, forces the other operand to be converted to a string.

3.4. Using Template Literals

Template literals in JavaScript are another excellent way to convert numbers to strings. By embedding a number inside a template literal, JavaScript automatically converts the number to a string.

Example:

let num = 1001;
let str = `${num}`;
console.log(str); // "1001"
console.log(typeof str); // string

Template literals are especially useful when you need to embed variables in strings or format strings dynamically.

4. Special Cases in Type Conversion

4.1. Empty String Conversion

In JavaScript, an empty string ("") can be converted into a number, and it behaves as 0.

Example:

let emptyStr = "";
let num = Number(emptyStr);
console.log(num); // 0

This behavior is important to note because it can lead to unintended results if you don’t account for the possibility of an empty string.

4.2. NaN (Not-a-Number)

When performing type conversions that involve invalid input, such as converting a non-numeric string to a number, the result will be NaN (Not-a-Number).

Example:

let invalidStr = "abc";
let num = Number(invalidStr);
console.log(num); // NaN

It’s crucial to handle NaN values properly, as they can affect calculations and logic in your program.

5. Best Practices for Type Conversion in JavaScript

To ensure your code is robust and error-free, here are some best practices to follow when converting strings to numbers and vice versa:

5.1. Validate User Input

Always validate user input before performing any conversion. Use functions like isNaN() to check if the input is a valid number.

let input = "abc";
if (isNaN(input)) {
  console.log("Invalid number input!");
} else {
  let num = Number(input);
  console.log(num);
}

5.2. Handle NaN Carefully

If there is a possibility of NaN resulting from a conversion, ensure you handle it appropriately to avoid errors.

5.3. Use the Right Method for the Job

Choose the conversion method that best fits the task. If you’re working with integers, use parseInt(). If you need to work with decimals, go with parseFloat(). When you need to convert strings to numbers quickly, consider using the unary plus (+) operator.

6. Conclusion

Understanding how to convert strings to numbers and numbers to strings is an essential skill in JavaScript programming. Whether you’re dealing with user inputs, mathematical operations, or manipulating data, the right conversion techniques will help you handle data efficiently.

We’ve covered the various methods for both conversions, from Number() and parseInt() to String() and toString(). With this knowledge in hand, you’ll be better equipped to handle data type conversions in your JavaScript applications.

JavaScript Conversion   Strings to Numbers   Number to String   JavaScript Best Practices   Type Conversion in JavaScript  
JavaScript Conversion   Strings to Numbers   Number to String   JavaScript Best Practices   Type Conversion in JavaScript  
 Truthy vs Falsy Values in JavaScript: Understanding Conditional Logic
JavaScript Strings Made Easy: Methods, Concatenation & Best Practices 

More Reading!

  1. How JavaScript Variables Actually Work: var vs let vs const
  2. JavaScript Strings Made Easy: Methods, Concatenation & Best Practices
  3. Let vs Var vs Const: Choosing the Right JavaScript Variable
On this page:
1. Introduction to Data Type Conversion in JavaScript 2. Converting Strings to Numbers in JavaScript 2.1. Using Number() 2.2. Using parseInt() 2.3. Using parseFloat() 2.4. Using the Unary Plus (+) Operator 2.5. Implicit Type Conversion (Type Coercion) 3. Converting Numbers to Strings in JavaScript 3.1. Using String() 3.2. Using toString() 3.3. Using String Concatenation 3.4. Using Template Literals 4. Special Cases in Type Conversion 4.1. Empty String Conversion 4.2. NaN (Not-a-Number) 5. Best Practices for Type Conversion in JavaScript 5.1. Validate User Input 5.2. Handle NaN Carefully 5.3. Use the Right Method for the Job 6. Conclusion
Follow me

I work on everything coding and technology

   
Mapagam
Mapagam is your go-to resource for all things related to frontend development. From the latest frameworks and libraries to tips, tutorials, and best practices, we dive deep into the ever-evolving world of web technologies.
Licensed under Creative Commons (CC BY-NC-SA 4.0).
 
Frontend
JavaScript 
Web Api 
TypeScript 
React 
Social
Linkedin 
Github 
Mapagam
Code copied to clipboard