Create a resume that lands you SDE interviews at MAANG

Speaker

Anubhav Sinha

SDE-2 @

12 Jun, 2024 @ 01:30 PM

Introduction

In programming, the data type of a variable frequently needs to be converted to another data type. This might be when a floating-point variable needs to be converted to an integer type and vice versa. There are multiple reasons why type conversions are implemented.

In this article, you will understand how to convert a String to Number in Javascript.

How to Convert String to Number in JavaScript?

In JavaScript, there are many built-in methods to convert string to number. It also has unary operator support to convert string to number.

The types of conversion in JavaScript to convert the string to number are:-

Implicit Conversion: In this method, the unary operator (+) is used before the string to convert it into number.

Explicit Conversion: All the operations did not automatically convert string to number in JavaScript. In this method, there are many in-built methods namely parseInt(), Number(), and parseFloat().

Now let us see all the string to number conversions in deep detail!!

Get the tech career you deserve, faster!

Connect with our expert counsellors to understand how to hack your way to success

User rating 4.7/5

1:1 doubt support

95% placement record

Akash Pal

Senior Software Engineer

326% Hike After Job Bootcamp

Himanshu Gusain

Programmer Analyst

32 LPA After Job Bootcamp

After Job Bootcamp

Approaches for the String to Number Javascript

There are 11 ways to convert a string to number in Javascript. Let us discuss each one by one:

1. Using parseInt() Function

The parseInt method parses a string value and returns the first integer. Leading and trailing spaces are not considered.

Syntax

parseInt( string, radix)

Parameters

String: Required. The value to be parsed

Radix: Optional. A radix parameter specifies the number system to be used:

It can convert null, boolean values (true and false), and all string representations of numbers into numbers. Integers, floats, hexadecimal, scientific (exponent) notation, and Infinity are acceptable numbers.

Syntax

+value

Return

NaN will be returned if the operand cannot be converted into a number.

The function Math.floor() returns the largest integer that is less/equal to a given number. This can be tricky with decimal numbers because it will return the nearest integer value as Number.

Syntax

Math.floor(value)

Parameters

value: Required. The value to be parsed.

Return

It returns a largest integer that is less than or equal to the parsed value. NaN if no number is found.

Example

str = '5555'
console.log(Math.floor(str))
a = '78.22'
console.log(Math.floor(a))

Output

6. Multiply the String With Number 1

To convert a string to a number in JavaScript using the method "Multiply the String With Number 1," you essentially use the implicit type coercion feature. By multiplying the string with the number 1, JavaScript coerces the string into a numeric value. This technique takes advantage of the fact that arithmetic operations in JavaScript typically work with numbers, triggering automatic type conversion.

This involves performing a division operation by dividing the string with the number 1. JavaScript automatically coerces the string to a numeric value during the operation.

Example

Javascript

Javascript

let strNumber = "42"; let convertedNumber = strNumber / 1; console.log(convertedNumber);

Output

8. Subtracting the Number 0 from The String

By subtracting 0 from the string, JavaScript implicitly converts the string to a number.

Example

Javascript

Javascript

let strNumber = "20"; let convertedNumber = strNumber - 0; console.log(convertedNumber);

Output

9. Using the Bitwise NOT Operator (~)

Applying the bitwise NOT operator (~) is an unconventional method. It converts the string to a 32-bit signed integer. Keep in mind that it might not be suitable for all scenarios, as it involves bitwise operations.

Example

Javascript

Javascript

let strNumber = "16"; let convertedNumber = ~strNumber; console.log(convertedNumber);

Output

10. Using Double tilde (~~) Operator

With the help of a tilde operator, we can convert a string to number in Javascript.

Example

str = '5555'
console.log(~~str)
a = '78.22'
console.log(~~a)

Output

11. Using the Math.ceil() Function

While Math.ceil() is typically used for rounding up numbers, applying it to a string can lead to implicit conversion. However, this method might not be as straightforward or commonly used as the others.

Example

Javascript

Javascript

let strNumber = "7"; let convertedNumber = Math.ceil(strNumber); console.log(convertedNumber);

Output

Comparison

You can refer to the image below to measure the performance of each method in comparison with each other.

Test

Ops/sec

A

var x = +"1000';

682, 485, 087

±0.87%

fastest

B

var x = Number("1000");

681,561,350

±0.85%

fastest

C

var x = Math.floor("1000");

94,940,907

±0.79%

86% slower

D

var x = parseInt("1000");

213,309,107

±1.50%

69% slower

E

var x = 1*"1000";

686,935,569

±1.06%

fastest

F

var x = ~~"1000";

686,712,736

±0.88%

fastest

Read More About, Basics of Javascript Let us now discuss some faqs based on the discussion above.

Frequently Asked Questions

What is the difference between parseInt() and parseFloat() in JS?

The only difference between parseInt() and parseFloat() is their parsing behaviour, not their return values. For example: parseInt(22.5) will return 22, whereas when using parseFloat(22.5) will return 22.5.

What is the fastest way to convert string to number in JavaScript?

The fastest way to convert a string to a number in JavaScript is often using the unary plus operator (+) or Number() function.

Does JavaScript automatically convert string to number?

Yes, JavaScript can convert string to number automatically using a process called as implicit type conversion. But some operations require explicit conversion using the Number(), parseInt(), parseFloat() functions.

How to convert empty string to number in JavaScript?

To convert an empty string to a number in JavaScript, use parseFloat("") or parseInt(""), both resulting in NaN (Not a Number).

Conclusion

To conclude the article, we have extensively discussed How to convert string to number in Javascript. We discussed 7 ways to convert a string to number with live examples.

This blog has helped you enhance your knowledge of conversion between a string to number in Javascript. If you want to learn more, then check out our articles.