supposing I have variable ex1
equal to -20 and variable ex2
equal to 50. I try to add it in javascript as alert(ex1+ex2);
but it alerts -20+50
. I'm really confused with this. THanks for the help, even though it might be a really silly question.
Asked
Active
Viewed 1.9k times
6

rnldpbln
- 654
- 3
- 11
- 22
2 Answers
14
JavaScript is a weakly typed language. So, you have to be careful with the types of data which you use. Without knowing much about your program, this can be fixed like this
alert(parseInt(ex1, 10) + parseInt(ex2, 10));
This makes sure that both ex1
and ex2
are integers. If you think, you would be using floating point numbers
alert(parseFloat(ex1) + parseFloat(ex2));

thefourtheye
- 233,700
- 52
- 457
- 497
-
7Don't forget the radix with `parseInt()`, though `parseFloat()` might be a better choice. – David Thomas Feb 27 '14 at 09:44
-
2@DavidThomas I was just adding that in the edit :) – thefourtheye Feb 27 '14 at 09:45
-
Right parseInt! Thanks! I will give you the correct answer once the 10 mins is up. Sorry that was a really dumb question btw. – rnldpbln Feb 27 '14 at 09:47
-
Downvoter, please let me know how I can improve this answer. – thefourtheye Feb 27 '14 at 10:56
1
Change your code like this
alert(parseInt(ex1) + parseInt(ex2));

MusicLovingIndianGirl
- 5,909
- 9
- 34
- 65