Posts Tagged: add subtract in javascript


28
Mar 08

How to perform mathematical operations in javascript?

You might come across a situation wherein you need to perform some mathematical operations on the data entered by the user. Be it addition, subtraction , multiplication or division, you can do these calculations using Javascript easily.

Since all the variables in JavaScript are declared using ‘var’ as a datatype, we need to use a function to tell Javascript to treat the contents of the variable as a number on which calculations have to be performed.

All you need to do is to use the ‘Number()’ function.

The example below will make things clear for you :

var a = “5″;

var b = “5″;

var result = a + b;

alert(“The result is “+result); // This will give you an output of 55 and not 10.

var calculatedResult = Number(a) + Number(b);

alert(“The mathematical result is “+calculatedResult); //This will give the result as 10.