Wednesday, April 9, 2008

Converting javascript string to int

Well it seems sometimes good to know all the basics before you go and do something. But most of the time people won't understand the basics until they come across a problem because of not knowing the basics. I'm these days working on a code base, where original developer no longer available. Time to time I get funny error. Yesterday when we checked interfaces after sometimes, I noticed that date is in correct. Actually it showed 1st of April! It worked fine last month!
So had to dig down to the code base and start debugging. Finally I figured out that it was a error due to Javascript string to int conversion. Consider these examples.
  1. parseInt('08',10)  // 8
  2. parseInt('8',8)    // 0 
  3. parseInt('08')     // 0
In our case, developer had used 3rd method where as he should have used first! Below is a total list of examples extracted from http://www.kourbatov.com/faq/convert2.htm

  1. parseInt('123.45')  // 123
  2. parseInt('77')      // 77
  3. parseInt('077',10)  // 77
  4. parseInt('77',8)    // 63  (= 7 + 7*8)
  5. parseInt('077')     // 63  (= 7 + 7*8)
  6. parseInt('77',16)   // 119 (= 7 + 7*16)
  7. parseInt('0x77')    // 119 (= 7 + 7*16)
  8. parseInt('099')     // 0 (9 is not an octal digit)
  9. parseInt('99',8)    // 0 or NaN, depending on the platform
  10. parseInt('0.1e6')   // 0
  11. parseInt('ZZ',36)   // 1295 (= 35 + 35*36)

No comments: