Rounding returned value from jquery.css

So just found out the problem I was having, and came up with a solution (bandaid really) but would like to know if anyone else has run into this and what they did.


var left_margin = $(this).css('margin-left').replace(/\\D/g,'');

So the above, get the left margin of the object, strip all but numbers and store into a variable. Easy, right?

Here’s what happened. Inserted the object into the DOM, Chrome returned 212px, which was converted to 212…*fine. Firefox on the other hand returned 212.5px, which was converted to 2125… not fine.

I’m centering the element on the screen based on this number, so the additional 2000ish pixels is WAY off. My solution was to increase one of my initial values a single pixel in which both browsers return 213px…*but like I said this is only a bandaid solution.

Not really understanding the value of .5 pixel, but looking into that. Is there a rounding function in jquery? Javascript I would have to strip the px from the string, convert to integer and THEN round.

Anyone have a hint?

Thanks

Some browsers are a little bit more precise :stuck_out_tongue:

But seriously, this usually happens when the result of an equation with fractions has set the value in question. It’s quite often moot though because AFAIK most browsers either ignore the fraction or round it internally.

If you wanted to get the whole number, rather than doing a regex, try the parseInt() method :slight_smile:

var left_margin = parseInt($(this).css('margin-left'));

Alternatively, you could just remove the “px” string from the end.

var left_margin = $(this).css('margin-left').replace("px","");

I’m surprised a fraction was returned for a pixel quantity.

Try:

var left_margin = $(this).css('margin-left').replace( /^(\\d+).*/g, '$1' );

went with the parseInt(). Seems like the right tool for the job in this case.

Still find it odd how a browser can return a half a pixel as a value (no matter how precise it may be).

Thanks.