int() is hard!

TorgoX on 2005-05-20T08:18:28

Dear Log,

Why JavaScript's parseInt() isn't Perl's int():

parseInt( 1 / 30000000 ) returns the numeric value 3.

Why?

Because 1 / 30000000 is is 3.3333333333333334e-8, which stringifies as "3.3333333333333334e-8", which parseInt sees as "3" plus junk, and so returns the integer 3.

Instead, I suggest something like:

 function _int (s) {
  return(
    (isNaN(s) || !isFinite(s)) ? undefined
    : (s == 0) ? 0
    : (s >  0) ? Math.floor(s)
    : (s <  0) ? Math.ceil( s)
    :            undefined
    );
 };


Nomenclature

Aristotle on 2005-05-21T06:52:25

I’d call that trunc. Or even assign it to Math.trunc.

Re:Nomenclature

TorgoX on 2005-05-24T04:47:30

I like the way you think!