Convert a String to a Number in JavaScript
Convert a String to a Number in JavaScript is a common and simple operation. When you are working with the real project at that time you have to manage the data whereas you need to convert a string to a number or a number to a string in JavaScript. So today we will show you how to convert a string to a number in JavaScript with example.
Convert a String to a Number in JavaScript, Converting strings to numbers with vanilla JavaScript, JavaScript Number() function, JavaScript parseInt() Function ,JavaScript parseFloat() Function, fastest way to convert String to Number.
Checkout more articles on JavaScript/ReactJS:
Why we need type conversion?
In Javascript, numbers can represent as actual number i.e. 28
or as string i.e."28"
. these are two different types of object so we use comparison to compare this number, it will fail.
let’s look at one example.
1 2 3 4 5 6 7 | var num1 = 28; var num2 = '28'; if (num1 === num2) { console.log(true); } else { console.log(false); } |
To overcome this issue, we need type conversion here.
Type of methods to convert a string into a number
Method 1: Number()
The Number() method is a function that converts the object argument to a number that represents the object’s value. if you pass in a string with random text in it you will get NaN
. so if The Number() function can’t converted to a number, NaN
is returned.
1 2 3 4 5 6 | var num1 = "28"; console.log(typeof(num1)) // Output: "string" var num2 = Number("28"); console.log(num2); // Output: 28 console.log(typeof(num2)); // Output: "number" |
Here we pass string 28 to Number() function and it returns a new number value of 28
. If we checked the typeof the new number you will find that is number
.
Method 2: parseInt()
Method parseInt() method is a function that parses a string and returns an integer with a specific radix. parseInt() function returns NaN
when the string doesn’t contain number.
1 2 3 4 | parseInt("28") // Output: 28 parseInt("28.51") // Output: 28 parseInt("28em") // Output: 28 parseInt("28.7xyz") // Output: 28 |
In the above four example, strings were converted to a 28
number. If we use Number() function for above last two examples then it returns NaN
so comparatively parseInt() function is better then Number() function.
Method 3: parseFloat()
parseFloat() is a function, which purses a string and returns a floating point number. Also parseFloat() function returns NaN
when the string doesn’t contain number.
1 2 3 4 | parseFloat("28") // Output: 28 parseFloat("28.51") // Output: 28.51 parseFloat("28em") // Output: 28 parseFloat("28.7xyz") // Output: 28.7 |
If you want to retain the decimal part and not just get the integer part, use parseFloat() function.
Thanks for reading and happy coding!