parseInt alternative

Cast it to an int in PHP before you json_encode() it:

$foo->bar = (int)$foo->bar;
print('var foo = ' . json_encode($foo));

Incidentally, when using parseInt it's good practice to always specify the second parameter unless you really want string starting with 0 to be interpreted as octal and so on:

parseInt('010', 10); // 10

To convert to an integer simply use the unary + operator, it should be the fastest way:

var int = +string;

Conversions to other types can be done in a similar manner:

var string = otherType + "";
var bool = !!anything;

More info.


Type casting in JavaScript is done via the constructor functions of the built-in types without new, ie

foo.bar = Number(foo.bar);

This differs from parseInt() in several ways:

  • leading zeros won't trigger octal mode
  • floating point values will be parsed as well
  • the whole string is parsed, i.e. if it contains additional non-numeric characters, the return value will be NaN

First off, have you actually documented that it's slow and is causing problems? Otherwise, I wouldn't bother looking for a solution, because there really isn't a problem.

Secondly, I would guess that since parseInt is a native JS-method, it would be implemented in a way that is very fast, and probably in the native language of the VM (probably C, depending on the browser/VM). I think you could have some trouble making a faster method out of pure JS. =)

Of course, I'm not a JS guru, so I don't know for sure, but this is what my intuition tells me, and tends to be the standard answer to "how would I make a faster alternative for libraryFunction()?" questions.