The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Using parseInt in script but getting NaN result

jtrezza
Kilo Contributor

I am writing a script to add a simple series of form data. I am very new to scripting, but this seemed pretty straight forward. Any thoughts as to what I did wrong?

//this script calculates the total amount of departmental allocations and only allows submit if total value = 100%

function onSubmit() {

var pc1 = parseInt(g_form.getValue('variables.hr_percentage'), 10);
var pc2 = parseInt(g_form.getValue('variables.hr_percentage_2'), 10);
var pc3 = parseInt(g_form.getValue('variables.hr_percentage_3'), 10);
var pc4 = parseInt(g_form.getValue('variables.hr_percentage_4'), 10);
var pc5 = parseInt(g_form.getValue('variables.hr_percentage_5'), 10);
var pc6 = parseInt(g_form.getValue('variables.hr_percentage_6'), 10);

var tot = pc1 + pc2 + pc3 + pc4 + pc5 + pc6 ;

if(tot != '100'){

alert (tot) ;
alert('Total allocation amounts must equal 100%, please adjust the values and re-submit.');
return false;

}else{
return true;
}}

13 REPLIES 13

Mark Stanger
Giga Sage

At a glance, I don't know what else might be wrong, but you're trying to compare your integer to a string ('100') at the end. Try removing the quotes here so that 100 is treated as an integer, not a string.

if(tot != '100'){


jtrezza
Kilo Contributor

Hey Mark thanks for the quick reposnse. I thought of that as well and removed the ' ' but no difference.
I threw the alert (tot) ; in there just to see what its doing and the result is NaN


I am experiencing a similar problem with the parseInt function.
If you print the value of intDayofmonth it will show NaN.
I use string comparisons to get around it.

var project_start_date = gs.now();
var strDayofmonth = project_start_date.toString().substr(8,2); //yyyy-mm-dd

// this statement will not return a valid int
var intDayofmonth = parseInt(strDayofmonth);

// must compare to strings, since parseInt returns NAN
if (strDayofmonth>'07' && strDayofmonth<'15') {
}


CapaJC
ServiceNow Employee
ServiceNow Employee

Hmm...I just tried your script, and printed "12".



var project_start_date = gs.now();
var strDayofmonth = project_start_date.toString().substr(8,2); //yyyy-mm-dd
var intDayofmonth = parseInt(strDayofmonth);
gs.print(intDayofmonth);