gbeke
Enthusiast
Enthusiast

Padd string with zeroes

Jump to solution

Hi,

When requesting a server the user is required to type in the number of the server as a string value. We need to be able to pad this string (number) with zeros so that the length is always 4.

Examples:

The user types in 1, the result should be 0001.

The user types in 56, the result should be 0056.

I've tried using padStart but get the error: Cannot find function padStart in object.

I've also tried functions lik this but it does not pad the number:

function padDigits(number, digits) {
  
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}

Is there a way to accomplish this with Orchestrator 7.5?

Any help will be greatly appreciated.

Thanks in advance.

gb

0 Kudos
1 Solution

Accepted Solutions
gbeke
Enthusiast
Enthusiast

Just after posting I stumbled across this function that works. It may not be the best way or most efficient, but it works and we're happy with that.

function ZeroPadNumber ( nValue )
{
  
if ( nValue < 10 )
  
{
  
return ( '000' + nValue.toString () );
  
}
  
else if ( nValue < 100 )
  
{
  
return ( '00' + nValue.toString () );
  
}
  
else if ( nValue < 1000 )
  
{
  
return ( '0' + nValue.toString () );
  
}
  
else
  
{
  
return ( nValue );
  
}
}

View solution in original post

0 Kudos
3 Replies
gbeke
Enthusiast
Enthusiast

Just after posting I stumbled across this function that works. It may not be the best way or most efficient, but it works and we're happy with that.

function ZeroPadNumber ( nValue )
{
  
if ( nValue < 10 )
  
{
  
return ( '000' + nValue.toString () );
  
}
  
else if ( nValue < 100 )
  
{
  
return ( '00' + nValue.toString () );
  
}
  
else if ( nValue < 1000 )
  
{
  
return ( '0' + nValue.toString () );
  
}
  
else
  
{
  
return ( nValue );
  
}
}

0 Kudos
qc4vmware
Virtuoso
Virtuoso

I use this code for padding.   You can pad to the left, right, or both directions.  Just create an action with inputs for len (length), pad (character to pad with), dir (direction to pad ) and str as the source string.  I'll attach the action as well.

var STR_PAD_LEFT = 1;

var STR_PAD_RIGHT = 2;

var STR_PAD_BOTH = 3;

if (typeof(len) == "undefined") { var len = 0; }

if (typeof(pad) == "undefined") { var pad = ' '; }

if (typeof(dir) == "undefined") { var dir = STR_PAD_RIGHT; }

if (len + 1 >= str.length) {

switch (dir){

case STR_PAD_LEFT:

str = Array(len + 1 - str.length).join(pad) + str;

break;

case STR_PAD_BOTH:

var right = Math.ceil((padlen = len - str.length) / 2);

var left = padlen - right;

str = Array(left+1).join(pad) + str + Array(right+1).join(pad);

break;

default:

str = str + Array(len + 1 - str.length).join(pad);

break;

} // switch

}

return str;

0 Kudos
gbeke
Enthusiast
Enthusiast

Great, thanks a lot! I will save this for testing later. We are going live today and it is working for us, so I don't want to change anything now.

0 Kudos