JS: How to add negative numbers in javascript

Suppose the variable ex1is -20 and the variable ex2is 50. I am trying to add it to javascript like alert(ex1+ex2);, but it warns -20+50. I am really confused by this. Thanks for the help, although this can be a really stupid question.

+4
source share
2 answers

JavaScript is a weakly typed language. Therefore, you must be careful with the types of data you use. Without knowing about your program, this can be fixed as follows:

alert(parseInt(ex1, 10) + parseInt(ex2, 10));

This ensures that both ex1and ex2are integers. If you think you will use floating point numbers

alert(parseFloat(ex1) + parseFloat(ex2));
+7

alert(parseInt(ex1) + parseInt(ex2));
+1

Source: https://habr.com/ru/post/1529176/


All Articles