Different ways to convert string into number in javascript

In JavaScript, there are different ways to convert a string into a number but the method you choose is depends on the specific requirements of your code.

Javascript image

Here are some different ways to convert a string to a number:

  • parseInt() and parseFloat()
  • Unary Plus (+)
  • Number() constructor
  • parseInt() with a radix (base)
  • parseFloat() for decimal numbers
  • Number.parseInt() (ES6)
  • Number.parseFloat() (ES6)
Let us discuss one by one with examples.

1. parseInt() and parseFloat():

parseInt() parses a string and returns an integer and parseFloat() Parses a string and returns a floating-point number. Consider following example for better understanding.
let str = "123";
let num = parseInt(str);
let floatNum = parseFloat("3.14");

console.log(num);
console.log(floatNum);

2. Unary Plus (+) :

The unary plus operator is used to convert a string to a number. Consider following example for better understanding.
let str = "456";
let num = +str; //output : 456

3. Number() constructor :

The Number() constructor can be used to explicitly convert a string to a number. Consider following example for better understanding.
let str = "789";
let num = Number(str); //output : 789

4. parseInt() with a radix (base) :

You can use parseInt() with a specified radix to convert a string to a number with a specific base (e.g., binary, octal, or hexadecimal).

Consider following syntax/example for better understanding.
let binaryStr = "1010";

//convert binary to decimal
let decimalNum = parseInt(binaryStr, 2); // output : 10

5. parseFloat() for decimal numbers :

parseFloat() can be used to ensure that string is converted to a decimal number. Consider following example for better understanding.
let str = "3.14";
let num = parseFloat(str); //output : 3.14

6. Number.parseInt() (ES6) :

Number.parseInt() is introduced in ES6 and it's a modern way of using parseInt() for string-to-number conversion. Consider following example for better understanding.
let str = "42";
let num = Number.parseInt(str); //output : 42

7. Number.parseFloat() (ES6) :

Number.parseFloat() is a modern way of using parseFloat() for string-to-number conversion. Consider following example for better understanding.
let str = "2.718";
let num = Number.parseFloat(str); //output : 2.718
Thanks for reading this article, if you found this article useful then share it with your friends and share your thoughts in comment section.

Want to learn more about javascript? checkout these amazing  Javascript Tutorials .

Comments