Skip to content Skip to sidebar Skip to footer

Parseint Alternative

Firstly - my description ;) I've got a XmlHttpRequests JSON response from the server. MySQL driver outputs all data as string and PHP returns it as it is, so any integer is return

Solution 1:

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

varint = +string;

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

varstring = otherType + "";
varbool = !!anything;

More info.

Solution 2:

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

Solution 3:

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.

Solution 4:

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

Solution 5:

Fast shortcut to parseInt is

("78.5" | 0) //bitwise or forces the string to parse as int

This is what ASM uses to represent ints in js.

Post a Comment for "Parseint Alternative"