Sunday, February 5, 2012

Converting String to Number in Javascript: A Gotcha

If you are used to program in C, Java, or any similar language, you might get surprised by the way Javascript's parseInt and parseFloat functions work. By their names, parseInt will convert a string into an integer, it does so by reading thorough the string and converts the characters to integer until it meets an invalid character, it then stops and returns the read characters (the valid part) as an integer, so
parseInt("123ax4");
will return 123.
This is a very different behavior than how Java, or C would work. So, if you see this dangerous, then there is a better way to do it. 

The Unary + Operator:
Using the unary + operator to convert strings to numbers guarantees you that either the entire string is a valid number, in such case the converted number value is returned as a result of the expression, or if there is any invalid number in the string, NaN is returned. So the output of the statement
+ "123";
results in the integer value 123. The output of the statement
+ "123a";
is NaN.