开发者

JQUERY Int and String Addition

Ok I have the following "script":

var text = '24 - 08';
var value = text.split(" - ");


var result = 24 - value[0];
result = result + value[1];
alert(result);

http://jsbin.com/amusaw/edit#javascript,html

So the result of this simple math thing is 0 with parseInt or 008 without it. It should be 8. I tried this开发者_高级运维 with several different numbers (instead of 08, 04 or 05 etc...) or 22 - 09.

Sometimes the result value is right and sometimes it's not. I tried to apply parseInt to all "math operations" ... no success. I think it's a tiny error, but I don't get it :(


Make sure you specify the base when parsing ints:

parseInt(value[0], 10);
parseInt(value[1], 10);

Whole code:

var text = '24 - 08';
var value = text.split(" - ");


var result = 24 - parseInt(value[0], 10);
result = result + parseInt(value[1], 10);
alert(result);

http://jsbin.com/amusaw/2/edit

When an string begins with a 0 parseInt assumes the number is octal (base 8). It's deprecated behaviour, but it is the way it behaves at any rate. The number 08 is invalid in octal since only the digits 0-7 exist, so it just returns 0. It determines that the 8 isn't part of the number, it is just like seeing 0A or 0T (or any other non 0-7 character).

More on parseInt(): https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt. In fact you can find the parseInt("08"); example that caused the problem for you right near the bottom of that page.


This seems to works using parseFloat instead of parseInt. You can do :

var result = 24 - parseFloat(value[0]);
result = result + parseFloat(value[1]);
alert(result);

You can then convert to int with a parseInt.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜