Search code examples
javascriptphotoshopphotoshop-script

Padding filename with Zeros for Integers with decimals


May someone help me with this issue I'm having with a Photoshop script for file naming?

What I am trying to do is add padding zeros to my filename that has whole numbers and decimals. This is what I have so far:

//Add leading zeros
function zeroPad(num) {
    var tmp = num.toString();
    while (tmp.length < 3) {tmp = '0' + tmp;}
    return tmp;
}

The problem is that this only works for files that only have whole numbers. If my filename has a decimal, it would just ignore it all together.

EX: With this script: doc36.jpg > doc036.jpg, but doc40.560.jpg > doc40.560.jpg

Thanks a bunch!


Solution

  • You need to pad only the integer portion of the number to get your expected result. So, check if it has a dot, if it does, split it and only pad the first part. If it doesn't, pad the whole number:

    function zeroPad(num) {
        var stringRep = num.toString();
        if (stringRep.indexOf(".") !== -1) {
            var tmp = stringRep.split(".");
            while (tmp[0].length < 3) {tmp[0] = '0' + tmp[0];}
            return tmp[0]+"."+tmp[1];
        }
        else {
            while (stringRep.length < 3) {stringRep = '0' + stringRep;}
            return stringRep;
        }
    }
    console.log(zeroPad(10));
    console.log(zeroPad(1.3));
    console.log(zeroPad(110));
    console.log(zeroPad(10.4));
    console.log(zeroPad(11234.4));