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

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'));

Prateek kumar
Mega Sage

It is documented here:

https://hi.service-now.com/kb_view.do?sysparm_article=KB0687726


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

Ashutosh Munot1
Kilo Patron
Kilo Patron

HI,

 

var a = '0' + i; '0' will be treated as string.

 

Why 0 is in quotes. It should not be in quotes. 

 

I ran below script:

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

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

 

Output:

019-09-18T18:03:39.035Z: a = 0; b = 0
2019-09-18T18:03:39.035Z: a = 1; b = 1
2019-09-18T18:03:39.035Z: a = 2; b = 2
2019-09-18T18:03:39.035Z: a = 3; b = 3
2019-09-18T18:03:39.035Z: a = 4; b = 4
2019-09-18T18:03:39.035Z: a = 5; b = 5
2019-09-18T18:03:39.035Z: a = 6; b = 6
2019-09-18T18:03:39.035Z: a = 7; b = 7
2019-09-18T18:03:39.035Z: a = 8; b = 8
2019-09-18T18:03:39.035Z: a = 9; b = 9
2019-09-18T18:03:39.035Z: a = 10; b = 10



Thanks,
Ashutosh

ryannnnnnnnnnnn
Tera Contributor

Zero is quoted to make a zero-padded string, which you will encounter in things like dates. For instance "01/01/2019"