In this article, we are going to explore various methods to convert a string into a number using JavaScript. Let's dive into four different approaches to achieve this task.

Convert String Into Number Using Parseint() Method

The parseInt() function is a fundamental method to convert a string to an integer in JavaScript.

<script>
  const str = "123";
  const num = parseInt(str);
  console.log(num)
</script>

1. Use parseInt() function.
2. Pass the string as an argument.
3. Assign the result to a variable.

Convert String To Number Using parsefloat() Method

If your string contains decimal numbers, parseFloat() is the go-to method.

<script>
  const str = "123.45";
  const num = parseFloat(str);
  console.log(num)
</script>
  1. Utilize parseFloat() function.
  2. Provide the string with decimal values.
  3. Store the result in a variable and console it.

How To Convert String To Number Using The Number() Method

The Number() method is a versatile way to convert strings to both integers and floats.

<script>
  const str = "123.45";
  const num = Number(str);
  console.log(num)
</script>
  1. Use the Number() method.
  2. Pass the string to be converted.
  3. Store the result in a variable.

Using the parseFloat() with Math.floor() method

Combining parseFloat() with Math.floor() ensures you get the integer part of a string with a floating-point number.

<script>
  const str = "123.45";
  const num = Math.floor(parseFloat(str));
  console.log(num)
</script>
  1. Use parseFloat() method to handle decimals.
  2. Apply Math.floor() to round down.
  3. Store the result in a variable.

Conclusion:

In this article, you learned four different methods to convert a string into a number in JavaScript.