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.

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.

To overcome this issue, we need type conversion here.

Type of methods to convert a string into a number

  1. Number()
  2. parseInt()
  3. parseFloat()

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.

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.

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.

If you want to retain the decimal part and not just get the integer part, use parseFloat() function.

Thanks for reading and happy coding!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *