Integer field is removing the leading zeroes of a number

Nani7
Tera Contributor

Experts,

I'm facing an issue with the integer type field type which is removing the leading zeroes of a number.

Example, if I enter 004498, it is getting updated as "4498".

I have to do an action that would need to increment this value using a server side script. So, if a run a BR, this value should be updated as "004499" and not "4499".

Any suggestions or alternatives?

- Nani

 

1 ACCEPTED SOLUTION

Hi,

this should work fine

var currentValue = "002100";
gs.info("Current Value: " + currentValue);

var zeroArray = [];

for(var i=0;i<currentValue.length;i++){

if(parseInt(currentValue.charAt(i)) == 0){
zeroArray.push(currentValue.charAt(i).toString());
continue;
}
else{
break;
}
}

var number = currentValue.replace(/^0+/, ''); // remove leading zeros
gs.info("Number: " + number);

number = parseInt(number) +1; // increment by 1

var finalValue = zeroArray.toString().replaceAll(',','') + number;

gs.info("Final Value: " + finalValue);

Output:

[0:00:00.084] Script completed in scope global: script


Script execution history and recovery available here


*** Script: Current Value: 002100
*** Script: Number: 2100
*** Script: Final Value: 002101

Regards
Ankur

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

View solution in original post

12 REPLIES 12

Brad Bowman
Kilo Patron
Kilo Patron

To retain the leading zeroes you'll need to change the field type to String, then you can do a regex validation if necessary to ensure that only numbers are entered in this field.

Thanks Brad... But I wanted to increment the value of the number. Eg. 004498 should be updated as 004499 again. How can I do this with a string value in the same number format?

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

make the field type as string and then use this

1) get all the leading zeros

2) then update the value by 1

3) then add the leading zeros again to the incremented value and set

Regards
Ankur

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

Thanks Ankur... Is there a way to get this incremented automatically without the need of adding zeroes separately?

The problem with your solution could be that...

For eg.. I'm staring with 004498... At some point, it becomes 010000 in future...

Then I cannot add two leading zeroes in this case. It has to happen automatically!

Can you help me further?