I have a variable which stores the css value of a margin. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With