Pad length to ensure 5 values

mdjoseph12
Giga Contributor

Looking for the best way to pad the source value to ensure that the target value is 5 digits, I attempted using the script below:

 

var location = source.u_location;

for(i = location.length;i < 4;i ++){


location = '0' + location;

return location; 


}
1 ACCEPTED SOLUTION

Hi Joseph,

try this and let me know

answer = (function transformEntry(source) {
var maxLength = 5;
var location = padZeroes(source.u_location,maxLength);

function padZeroes(number, length) {
var my_string = '' + number;
while (my_string.length < length) {
my_string = '0' + my_string;
}
return my_string;
}

return location;

})(source);

Mark Correct if this solves your issue and also mark Helpful if you find my response worthy based on the impact.
Thanks
Ankur

 

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

View solution in original post

9 REPLIES 9

Hi Joseph,

try this and let me know

answer = (function transformEntry(source) {
var maxLength = 5;
var location = padZeroes(source.u_location,maxLength);

function padZeroes(number, length) {
var my_string = '' + number;
while (my_string.length < length) {
my_string = '0' + my_string;
}
return my_string;
}

return location;

})(source);

Mark Correct if this solves your issue and also mark Helpful if you find my response worthy based on the impact.
Thanks
Ankur

 

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Ankur Bawiskar
Tera Patron
Tera Patron

Hi Joseph,

so incoming value can be 2 or 3 or 4 digits and based on that you want to append 0 as prefix

Is the target field a integer field or string field?

Regards

Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

correct, and the target is an integer field 

Hi Joseph,

but why you want to add zeros in prefix; for an integer field it won't make any sense right?

Mark Correct if this solves your issue and also mark Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader

Its actually a string field