Possible Duplicate:
Strange javascript addition problem
I know there’s obviously a solution for this, and I’ve done it before, but I can’t remember it and now I can’t find it.
<div>1</div>
$(function() {
var number = $('div').text();
var math = number + 2;
$('body').text(math);
});
number is not being treated as an integer so math‘s value is “12” instead of “3”. How can I correct this?
There are many ways, but
is a simple one. Whether you should be detecting possible ill-formed non-numbers depends on the nature of the rest of your code.
The
parseInt()function is useful, but it probably should be called with 10 as its second argument to avoid interpreting numbers that begin with zero as octal constants instead of decimal. Also,parseInt()will not treat a string like “23skidoo” as an error, which may or may not be OK in your application.