Apr
04
2006

Javascript String to Int

Handy function:

var yourInt;
yourInt = parseInt(str);

More Info: http://www.devguru.com/Technologies/ecmascript/quickref/parseint.html

Share and Enjoy:
  • del.icio.us
  • digg
  • Furl
  • NewsVine
  • RawSugar
  • Reddit
  • Spurl
  • YahooMyWeb
Written by Tom in: Javascript |

12 Comments »

  • dav7

    Wow, thanks for that. First hit in Google and exact result to my problem (“start = parseInt(document.getElementById(‘text’).value);”).

    My function was returning an array with missing values when I tried to access `start – 1′ but as soon as I parseInt’ed it all was well \o/ :D

    -dav7

    Comment | May 20, 2007
  • Scott

    Perfect, thanks! I was lamenting having to use eval(), so this is perfect!

    Comment | May 20, 2007
  • Airor

    Instead I use the built in typecasting
    myInt = 0 + str;
    myStr = ” + i + ‘ number of things.’;

    Comment | October 5, 2007
  • Leonardo

    Nice one,
    tkx

    Comment | January 22, 2008
  • johnsmith

    Ja pierdole ale niemoc pisać tak zjebane artykuły.

    Nice :)

    Comment | July 10, 2008
  • norma savage

    thanks!
    :)

    Comment | July 15, 2008
  • Barnaby

    haha, to jest całkiem bez sensu artykuł

    Pretty cool, thanks :-)

    Comment | September 13, 2008
  • ———————————–
    var yourInt;
    yourInt = parseInt(str);
    ———————————–

    You can not use this code fragment if your string is “009″. parseInt(“099″)=0;
    Because “000″ not is a octal digits.

    Thanks.

    Comment | September 26, 2008
  • Sorry, I mean : Because “099″ not is a octal digits.

    Comment | September 26, 2008
  • Istvan

    You should always explicitly specify the radix to be safe:

    var yourInt;

    yourInt = parseInt(str,10);

    In this case you won’t have problems with strings that can be interpreted as octal numbers.

    From the javascript specification:

    If the radix parameter is omitted, JavaScript assumes the following:

    If the string begins with “0x”, the radix is 16 (hexadecimal)

    If the string begins with “0″, the radix is 8 (octal). This feature is deprecated

    If the string begins with any other value, the radix is 10 (decimal)

    Not all browsers implement the specification in the same way, so if you want your code to work consistently everywhere you shouldn’t omit the radix.

    Comment | October 23, 2008
  • thank you so much lstvan. i was kicking myself trying to see why 08 was returning 0. you rule.

    Comment | November 22, 2008
  • I&Mdesign

    Thanks a lot for your explanation about hexadecimal and octal numbers espesially. It works!

    Comment | December 4, 2008

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress | Aeros Theme | TheBuckmaker.com WordPress Themes