开发者

Dealing with Negative Numbers in Strings

开发者 https://www.devze.com 2022-12-13 20:17 出处:网络
I have a simple, but perplexing problem, with Math. The following code will take a number from a string (usually contained in a span or div) and subtract the value of 1 from it.

I have a simple, but perplexing problem, with Math.

The following code will take a number from a string (usually contained in a span or div) and subtract the value of 1 from it.

.replace(/(\d+)/g, function(a,n){ return (+n-1); });

This works really well, except when we get below zero. Once we get to -1 we're obviously de开发者_如何转开发aling with negative subtraction.

-1 - 1 = -0

-0 - 1 = --1

how can I avoid this? It's likely I've got a general problem with the math here.


The problem is that your function is not treating "-1" as negative one - it's being treated as a hyphen followed by positive 1.

/(-?\d+)/g will capture a leading hyphen as well.


Your .replace(/(\d+)/g) isn't capturing the leading -. If you want your addition to be correct, you'll need something like /(-?\d+)/.

0

精彩评论

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

关注公众号