How to add two strings as if they were numbers? [duplicate]

ghz 1years ago ⋅ 114 views

Question

This question already has answers here :

[Adding two numbers concatenates them instead of calculating the sum](/questions/14496531/adding-two-numbers-concatenates-them-instead-of- calculating-the-sum) (24 answers)

Closed 3 years ago.

I have two strings which contain only numbers:

var num1 = '20',
    num2 = '30.5';

I would have expected that I could add them together, but they are being concatenated instead:

num1 + num2; // = '2030.5'

How can I force these strings to be treated as numbers?


Answer

I would use the unary plus operator to convert them to numbers first.

+num1 + +num2;