123

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;
John Himmelman
  • 21,504
  • 22
  • 65
  • 80

6 Answers6

235

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

parseInt(a, 10);
FaerAnne
  • 66
  • 7
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 4
    Everyday in everyway Im loving you more and more javascript – James Westgate Jun 11 '10 at 16:29
  • 3
    @lsiden: it does work. `parseInt("20em", 10) === 20` and `parseInt("20pt", 10) === 20`. Feel free to paste either expression into your favourite browser's console, or see [this very short example](http://jsfiddle.net/8Rqz4/). Whatever problem you're having lies elsewhere in your code. – Andy E May 20 '11 at 22:57
  • 8
    A sidenote, the `parseInt` function will actually disregard any non-integer characters appended to the end of a string of integer characters. `parseInt('234sdfsdf') == 234` – Chris W. Nov 18 '11 at 17:04
  • 3
    @AndyE: Isiden was saying that parseInt won't convert em values (or pt or others) in the equivalent pixel values, which is what some people may need. – LeartS Feb 09 '14 at 14:28
47

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
Roly
  • 2,126
  • 2
  • 20
  • 34
9
$.parseMethod = function (s)
{
    return Number(s.replace(/px$/, ''));
};

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

just somebody
  • 18,602
  • 6
  • 51
  • 60
7
 var c = parseInt(a,10);
unomi
  • 2,642
  • 18
  • 19
0

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!
MAChitgarha
  • 3,728
  • 2
  • 33
  • 40
-2
$(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.

Zippy
  • 1,804
  • 5
  • 27
  • 36