jQuery / Javascript - How do I convert a pixel value (20px) to a number value (20)

JavascriptJquery

Javascript Problem Overview


I know jQuery has a helper method for parsing unit strings into numbers. What is the jQuery method to do this?

var a = "20px";
var b = 20;
var c = $.parseMethod(a) + b;

Javascript Solutions


Solution 1 - Javascript

No jQuery required for this, Plain Ol' JS (tm) will do ya,

parseInt(a, 10);

Solution 2 - Javascript

More generally, parseFloat will process floating-point numbers correctly, whereas parseInt may silently lose significant digits:

parseFloat('20.954544px')
> 20.954544
parseInt('20.954544px')
> 20

Solution 3 - Javascript

$.parseMethod = function (s)
{
    return Number(s.replace(/px$/, ''));
};

although how is this related to jQuery, I don't know

Solution 4 - Javascript

 var c = parseInt(a,10);

Solution 5 - Javascript

Sorry for the digging up, but:

var bar = "16px";

var foo = parseInt(bar, 10); // Doesn't work! Output is always 16px
// and
var foo = Number(s.replace(/px$/, '')); // No more!

Solution 6 - Javascript

$(document).ready(function(){<br>
	$("#btnW1").click(function(){<br>
        $("#d1").animate({<br>
			width: "+=" + x,
			
		});
    });

When trying to identify the variable x with a pixel value I by using jquery I put the += in quotes. Instead of having width: '+= x', which doesn't work because it thinks that x is a string rather than a number. Hopefully this helps.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn HimmelmanView Question on Stackoverflow
Solution 1 - JavascriptAndy EView Answer on Stackoverflow
Solution 2 - JavascriptRolyView Answer on Stackoverflow
Solution 3 - Javascriptjust somebodyView Answer on Stackoverflow
Solution 4 - JavascriptunomiView Answer on Stackoverflow
Solution 5 - JavascriptAlain MazyView Answer on Stackoverflow
Solution 6 - JavascriptElliot SulsView Answer on Stackoverflow