Skip to main content
Participant
May 31, 2018
Answered

In Adobe scripting: How to get padded numbers (leading zeroes)?

  • May 31, 2018
  • 4 replies
  • 1671 views

In Adobe Photoshop scripting: How to get padded numbers (leading zeroes)?

I have tried these two solutions and neither work...

INDEX = util.printf("%04d", INDEX);

INDEX = "%04d".sprintf(INDEX);

Is there any way to make numbers with leading zeroes with Adobe javascript...?

Thanks for any help,

Rich

This topic has been closed for replies.
Correct answer SuperMerlin

Yet more methods...

var result=[];

for(var a = 1;a <11;a++){result.push(zeroPad(a,5));}

alert(result.join("\n"));

result=[];

for(var a = 1;a <11;a++){result.push(zeroPad2(a,15));}

alert(result.join("\n"));

function zeroPad(n, pad) {

if(pad == undefined) pad = 4;

n = n.toString();

while (n.length < pad) n = '0' + n;

return n;

};

function zeroPad2(num,pad) {

if(pad == undefined) pad = 4;

var z = Math.pow(10,Number(pad));

return num <= z ? ((Number( num) + z).toString().substr(1)): num;

};

4 replies

SuperMerlin
SuperMerlinCorrect answer
Inspiring
May 31, 2018

Yet more methods...

var result=[];

for(var a = 1;a <11;a++){result.push(zeroPad(a,5));}

alert(result.join("\n"));

result=[];

for(var a = 1;a <11;a++){result.push(zeroPad2(a,15));}

alert(result.join("\n"));

function zeroPad(n, pad) {

if(pad == undefined) pad = 4;

n = n.toString();

while (n.length < pad) n = '0' + n;

return n;

};

function zeroPad2(num,pad) {

if(pad == undefined) pad = 4;

var z = Math.pow(10,Number(pad));

return num <= z ? ((Number( num) + z).toString().substr(1)): num;

};

rkboboAuthor
Participant
June 1, 2018

These two functions work great - thanks!

May 31, 2018

The usual way is to prepend a series of extra zeroes to the number converted to a string (automatically done by the concatenation operator) then slice the resulting string from the end with the desired number of digits:

INDEX = ("0000" + INDEX).slice(-4)

This method is very often used to express numbers in fixed 4-digit hexadecimal format, like in Douglas Crockford's JSON implementation:

INDEX = ("0000" + INDEX.toString(16)).slice(-4)

HTH...

Legend
May 31, 2018

Does not work with negative numbers and with those that are greater than 9999

Legend
May 31, 2018

For example, the function expand_numbers() from this post

Re: Sort / Order Selected Layers (Alphabetically)?

alert(expand_numbers(INDEX, 4))
JJMack
Community Expert
Community Expert
May 31, 2018

Yes, Use the correct forum Photoshop Scripting

JJMack
rkboboAuthor
Participant
June 1, 2018

Sorry about that. First-time poster. Thought I picked the right one...