Tuesday, May 8, 2012

Do you want August to be part of a year or not?

Run this code

<html>
  <head>
    <script type="text/javascript">
      function getMonth() {
        var splittedDate = document.getElementById('inputDate').value.split('/');
        document.getElementById('parseInt1').innerHTML = 'parseInt(month) = ' + parseInt(splittedDate[1]);
        document.getElementById('parseInt2').innerHTML = 'parseInt(month, 10) = ' + parseInt(splittedDate[1], 10);
      }
    </script>
  </head>
  <body onload="getMonth()">
    <input type="text" value="2012/08/24" id="inputDate">
    <p>
      <div id="parseInt1"></div>
    </p>
    <p>
      <div id="parseInt2"></div>
    </p>
  </body>
</html> 

and see the results. Passing to parseInt the string '08' without specifying the second parameter will result in undesired integer.


parseInt(string, radix)

When radix is omitted then strings which start with '0' will be parsed in octal and the ones which start with '0x' will be parsed in hexadecimal.

Per Standard ECMA-262 5.1 edition:


15.1.2.2: The specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values. 

Make yourself a habit to pass the second parameter too to that function even if you are sure about the value of the first parameter.

No comments:

Post a Comment