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?
You can use this to add numbers:
You can use
parseInt
to parse a string to a number. To be on the safe side of things, always pass10
as the second argument to parse in base 10.I would use the unary plus operator to convert them to numbers first.
If you need to add two strings together which are very large numbers you'll need to evaluate the addition at every string position:
I use this in my project.I use + sign to treat string as a number (in with_interesst variable)
Hope it helps