Documenting Problems That Were Difficult To Find The Answer To

Beware JavaScript parseInt and Leading Zeros

I had some JavaScript code for breaking apart a timestamp (e.g. 11:07) into hours (11) and minutes (07).

function minutes_past_midnight( timestring ) {
  var result = /(\d+):(\d+)/.exec( timestring );
  if ( result == null )
    return null;

  var hours = parseInt( result[1] );
  var minutes = parseInt( result[2] );

  return( (hours * 60) + minutes );

But this function failed to correctly calculate when minutes were 08 or 09. That’s because parseInt, by default, treats numbers leading with zero as octal.

To fix this I changed my parseInt call to specify a radix parameter to force it to interpret in base-10.

  var hours = parseInt( result[1], 10 );
  var minutes = parseInt( result[2], 10 );

This strips out (skips) a leading zero in the hours and minutes so parseInt() will not see any leading zeros.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: