Jump to content

Addition Problem


mickeymouse
 Share

Recommended Posts

byyr contains 20. 

If I add 1, I get 201 (wrong result).  (See first set of code below)

If I multiply by 5, I get 100 (correct result).  (See second set of code below) 

If I multiply by 1, I get 100 (correct result). 

According to documentation, a + in Java Script is addition.

I have spent over 2 hrs trying to figure out what was wrong with my (more complicated) coding.

Please, please, tell me why addition doesn't work.

 

function mytab(byyr,bymo,mo,fld,to)
{with (byyr, bymo, mo, fld, to)
var x = byyr.value
var y = x + 1;
alert(y);}

function mytab(byyr,bymo,mo,fld,to)
{with (byyr, bymo, mo, fld, to)
var x = byyr.value; 
var y = x * 5;
alert(y);}

 

Link to comment
Share on other sites

"+" is used for string concatenation. If the values are strings then they will use the string version of the "+" operator. You have to convert the value to a number before operating in order for it to work as you intend it to.
 

var x = Number(byyr.value);
var y = x + 1;

 

  • Like 1
Link to comment
Share on other sites

  • 6 months later...

I like to use this hack when adding values in JS:

sum = -(-x - y);

It eliminates the ambiguous  '+' operator altogether, along with any type confusion.

It can also be put into a function:

function add(a, b) {return -(-a - b)}

sum = add(x, y);

This may be slightly less efficient than declaring the var as numeric, but I think it makes for neater code, and there are times we want to make use of JS's loose typing, so the var can be used as text in one place and numeric in another.

Edited by Jay@TastefulTitles.com
Link to comment
Share on other sites

You can also preceed the string with a + to convert it to a number.

For example:

	<script>
function mytab1(byyr,bymo) {
  var x = byyr,
      y = x + 1;     // expect 201
      z = +x +1;     // expect 21
  alert(y+' : '+z);
	  var a = bymo * 10; // expect 50
  alert(a);
}
	mytab1('20','5');  // test
</script>
	

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...