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?
Here, you have two options to do this :-
.
Now I am going to show you here with the help of examples(Find the sum of two numbers).
Using unary plus operator
Using parsing approach-
I've always just subtracted zero.
Granted that the unary operator method is one less character, but not everyone knows what a unary operator is or how to google to find out when they don't know what it's called.
try
or, depending on your needs:
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
I would recommend to use the unary plus operator, to force an eventual string to be treated as number, inside parenthesis to make the code more readable like the following:
So, in your case it's:
convert the strings to
floats
withparseFloat(string)
or tointegers
withparseInt(string)
If you want to perform operation with numbers as strings (as in the case where numbers are bigger than 64bits can hold) you can use the big-integer library.