Easy tech stuff!

How to perform mathematical operations in javascript?

Posted: March 28th, 2008 | Author: Nischal Shetty | Filed under: JavaScript | Tags: , , , | No Comments »

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.

http://www.techtamasha.com/wp-content/plugins/sociofluid/images/digg_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/reddit_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/stumbleupon_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/delicious_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/furl_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/technorati_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/google_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/myspace_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/facebook_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/yahoobuzz_48.png http://www.techtamasha.com/wp-content/plugins/sociofluid/images/twitter_48.png


Leave a Reply