I recently ran into a piece of code very much like this one:
var nHours = parseInt(txtHours);
if( isNaN(nHours)) // Do something
else // Do something else with the value
The developer who wrote this code was under the impression that nHours
would either be an integer that exactly matched txtHours
or NaN
. There are several things wrong with this assumption.
First, the developer left of the radix argument which means input of "09"
would result in a value of 0
instead of 9
. This issue can be resolved by adding the radix in like so:
var nHours = parseInt(txtHours,10);
if( isNaN(nHours)) // Do something
else // Do something else with the value
Next, input of "1.5"
will result in a value of 1
instead of NaN
which is not what the developer expected since 1.5
is not an integer. Likewise a value of "1a"
will result in a value of 1
instead of NaN
.
All of these issues are somewhat understandable since this is one of the most common examples of how to convert a string to an integer and most places don't discuss these cases.
At any rate it got me thinking that I'm not aware of any built in way to get an integer like this. There is Number(txtHours)
(or +txtHours
) which comes closer but accepts non-integer numbers and will treat null
and ""
as 0 instead of NaN
.
To help the developer out I provided the following function:
function ConvertToInteger(text)
{
var number = Math.floor(+text);
return text && number == text ? number : NaN;
}
This seems to cover all the above issues. Does anyone know of anything wrong with this technique or maybe a simpler way to get the same results?