SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    Learning...
    Join Date
    Jan 2003
    Posts
    781
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    parseInt question

    Hi,

    Why is the result of parseInt("08") is 0 and not 8?

    Thanks
    The beauty of life is not dependent on how happy you are,
    but on how happy others can be because of you...

  2. #2
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,108
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    Good question, I had no idea.
    https://developer.mozilla.org/en/Jav...jects/parseInt
    If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.

    I don't actually use parseInt, I use Number().

  3. #3
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,192
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    What you would actually want to be using is parseFloat as it automatically removes any zero's proceeding the number you want, see the following jsFiddle to see the result.

    http://jsfiddle.net/chrisupjohn/mXPLr/

  4. #4
    Learning...
    Join Date
    Jan 2003
    Posts
    781
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks guys!

    It was a question that i was asked and it got me confused.

    Now jsfiddle is showing 8 for it with default redix. Interesting!!!! I am going to spend some more time on it later in the evening.
    The beauty of life is not dependent on how happy you are,
    but on how happy others can be because of you...

  5. #5
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,820
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    parseInt is for converting from one number base to another. The second parameter specifies the base of the original number and the result will be base 10. If the second parameter is not specified then vamues starting with 0x will be treated as hexadecimal. If JavaScript is not running in strict mode then some but not all browsers will treat a leading zero as an indication that the numner is octal.

    If you are trying to convert a string to a number then a better function to use is Number('08) or even +'08'
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •