3

I always had this question:
When i dont mind the exact floating number

Which one is preferred?

parseFloat

    someValue  = parseFloat(el.outerWidth())+parseFloat(ele2.css("marginRight")),

parseInt

    someValue  = parseInt(el.outerWidth(), 10)+parseInt(ele2.css("marginRight"), 10),

Which method is easier for the JS engine?

adardesign
  • 33,973
  • 15
  • 62
  • 84

3 Answers3

3

It's as broad as it's long really. parseFloat is pointless here because the values will always be integers. I'd rather save on bytes and use the unary operator +:

someValue  = (+el.outerWidth())+(+ele2.css("marginRight"));
Community
  • 1
  • 1
Andy E
  • 338,112
  • 86
  • 474
  • 445
3

When you're doing: el.outerWidth() jQuery is already returning and integer, see the docs for return types. So in this case, there's no need to parse the width at all.

It should be noted, there's another overload of outerWidth(bool) that includes the margin if you want left and right margins, you can just do this if that's the case:

someValue = el.outerWidth(true);
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • correct in case of outerWidth(), but my question is general, anyway thanks. good point. – adardesign Mar 11 '10 at 15:32
  • 1
    @adardesign - In that case...you can't position any more accurately than a pixel, makes no sense to since that's what monitors display in. For layout properties in pixels, use `parseInt(val, 10);` – Nick Craver Mar 11 '10 at 15:33
3

The best solution is of course Andy E's solution, but to answer your question: I think parseFloat is pointless if your number have not a floating-point, so I would use parseInt.

The size of the variable is an important factor in those performance comparisons, but int and float take up the same space in the memory (4 bytes), so it dosen't really matter. In addition, parseFloat seems to do more calculating and string-parsing than parseInt.

Alon Gubkin
  • 56,458
  • 54
  • 195
  • 288
  • +1 Alon, "this" is the answer i really wanted to hear, the others where practical solutions to my question, "you" answered the question – adardesign Mar 11 '10 at 15:39