parseInt() doesn't work?!

ryannnnnnnnnnnn
Tera Contributor

Could anyone please tell me why parseInt() is not working?

for (var i = 0; i <= 10; i++) {
    var a = '0' + i;
    var b = parseInt(a);

    gs.log('a = ' + a + '; b = ' + b);
}

The output is:

*** Script: a = 00; b = 0
*** Script: a = 01; b = 1
*** Script: a = 02; b = 2
*** Script: a = 03; b = 3
*** Script: a = 04; b = 4
*** Script: a = 05; b = 5
*** Script: a = 06; b = 6
*** Script: a = 07; b = 7
*** Script: a = 08; b = NaN
*** Script: a = 09; b = NaN
*** Script: a = 010; b = 8

Thanks,

Ryan

1 ACCEPTED SOLUTION

Mike Allen
Mega Sage

Looks like it is octal, and you have to specify base 10:

 

for (var i = 0; i <= 20; i++) {
var a = '0' + i;
var b = parseInt(a,10);

gs.log('a = ' + a + '; b = ' + b);
gs.log(typeof a);
gs.log(typeof b);
}

gs.log(parseInt('10'));

View solution in original post

6 REPLIES 6

ryannnnnnnnnnnn
Tera Contributor

Thank you, Mike & Prateek!

 

Issue: this is a ServiceNow bug due to using a non-standard, out-of-date version of JavaScript, circa the year 2011.

 

In order to run correctly, the code needs to read:

 

var base = 10;
for (var i = 0; i <= 10; i++) {
    var a = '0' + i;
    var b = parseInt(a, base);

    gs.log('a = ' + a + '; b = ' + b);
}

Yep, Could you please mark the appropriate response as correct and close this thread.

 


Please mark my response as correct and helpful if it helped solved your question.
-Thanks