Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: How to add negative numbers in javascript [duplicate]

Tags:

javascript

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.

like image 581
rnldpbln Avatar asked Feb 27 '14 09:02

rnldpbln


2 Answers

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));
like image 175
thefourtheye Avatar answered Oct 05 '22 23:10

thefourtheye


Change your code like this

alert(parseInt(ex1) + parseInt(ex2));
like image 41
MusicLovingIndianGirl Avatar answered Oct 06 '22 01:10

MusicLovingIndianGirl