开发者

trim "px" off the end of Jquery var

I have a variable which stores the css value of a margin.开发者_如何学JAVA I want to remove the "px" from the end so that i just have the number to work with. How can i do this?


var x = "1px";
var y = parseInt(x, 10); // specify radix to prevent unpredictable behavior


Option 1:

parseInt('200px', 10);

The parseInt() function parses a string and returns an integer. Don't change the 10 found in the above function (known as a "radix") unless you know what you are doing.

Output will be: 200.

Option 2 (I personally prefer this option)

parseFloat('200px')

Output will be: 200

The parseFloat() function parses a string and returns a floating point number.

The parseFloat() function determines if the first character in the specified string is a number. If it is, it parses the string until it reaches the end of the number, and returns the number as a number, not as a string.

The advantage of Option 2 is that if you use decimal numbers (e.g. 200.32322px) you will get the number returned with the values behind the decimal point. Useful if you need specific numbers returned.


Using the String.replace() method is an easy way:

http://www.w3schools.com/jsref/jsref_replace.asp


You're better off using parseFloat()

In situations where you have decimals, like 0.5s for transition-delay, parseInt(x,10) returns zero, where in contrast parseFloat() returns 0.5

var x = "0.5s";
var y = parseFloat(x); //returns 0.5
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜