How to add leading zeros to a variable in a Business Rule

matthew_hughes
Kilo Sage

I'm wanting to add leading zeros to a particular variable within the below background script:

var child = new GlideRecord('u_cmdb_ci_architecture_domain');

child.addQuery('sys_id', 'c37a154e1bf4555009dd5e26464bcbf8');

child.query();

if(child.next())

{
var child1 = new GlideRecord('u_cmdb_ci_architecture_domain');
var total = 0;
var sum = 0;
var average = 0;
var factor5 = 0;
var RoadmapValue = '';

child1.addQuery('u_parent',child.sys_id);
child1.query();
while(child1.next())
{
RoadmapValue = parseFloat(child1.getValue('u_roadmap_realisation'));
total++;
sum+=RoadmapValue;
average = sum/total;
average = average.toFixed(3);
//average = Math.round(num/5)*5;
factor5 = Math.round(average/5)*5;
//factor5 = 0 + factor5
gs.info('Architecture Domain Child is: ' + child1.name);
gs.info('Roadmap value is: ' + RoadmapValue);
}
gs.info('Total is ' + total);
gs.info('Sum is ' + sum);
gs.info('Average is '+ average);
gs.info('factor5 is ' + factor5);
}

 

When I run the script, the output is as follows:

*** Script: Architecture Domain Child is: Test 1 child for SFSTRY0013063
*** Script: Roadmap value is: 65
*** Script: Architecture Domain Child is: Test 2 child for SFSTRY0013063
*** Script: Roadmap value is: 0
*** Script: Architecture Domain Child is: Another child test
*** Script: Roadmap value is: 5
*** Script: Total is 3
*** Script: Sum is 70
*** Script: Average is 23.333
*** Script: factor5 is 25


However, what I would like to see for the 'factor5' variable is leading zeros so that it displays as 025. I was wondering if there was a logic that could be applied so that the numbers appear as e.g. from 000 to 100

3 REPLIES 3

Mohith Devatte
Tera Sage
Tera Sage

Hello,

Try like this

factor5 = '0'+factor5 //add 0 as string

Then again declare a variable like below

var Factor6 =parseInt(factor5);// convert to integer

Please mark my answer correct if it helps you

Hi @Mohith Devatte ,

 

When I add Factor6 and run the script, it now comes back as:

*** Script: Architecture Domain Child is: Test 1 child for SFSTRY0013063
*** Script: Roadmap value is: 100
*** Script: Architecture Domain Child is: Test 2 child for SFSTRY0013063
*** Script: Roadmap value is: 0
*** Script: Architecture Domain Child is: Another child test
*** Script: Roadmap value is: 5
*** Script: Total is 3
*** Script: Sum is 105
*** Script: Average is 35.000
*** Script: factor5 is 035
*** Script: factor6 is 29

Can you share your script please