Put 00 on the left in another variable [duplicate]

0

I have an HTML form that receives the number according to the ID registered in SQL and saved in another variable, however the ID is sequential and without zero, for example:

ID 1
ID 2
ID 3

I needed to get this ID and put it in the Number variable as follows:

001
002
003

Would it be done via JS or could it be done directly via MySQL?

    
asked by anonymous 11.09.2017 / 22:54

1 answer

3

In mysql @rray already suggested

  

link

It would be something like in your case:

SELECT lpad('1', 3, 0)

In JavaScript you have this example link just make the adjustment for 3 zeros:

var input = '1';
var lpadresult = ('000' + input).slice(-3);

console.log(lpadresult);

4 digits:

var input = '1';
var lpadresult = ('0000' + input).slice(-4);

console.log(lpadresult);

Or an adapted function:

function strpad(input, size, right, prefix) {
    //o array gera os zeros para usar na frente ou depois
    var ps = Array(size).join(prefix ? prefix : "0");
    
    //Inverte para o sufixo
    if (right) {
        return (input + ps).slice(0, size);
    } else {
        return (ps + input).slice(-size);
    }
}

//3 prefixos
console.log(strpad('1', 3));
console.log(strpad('22', 3));
console.log(strpad('333', 3));
console.log(strpad('4444', 3));

console.log("-----------");

//4 prefixos
console.log(strpad('1', 4));
console.log(strpad('22', 4));
console.log(strpad('333', 4));
console.log(strpad('4444', 4));

console.log("-----------");

//3 sufixos
console.log(strpad('1', 3, true));
console.log(strpad('22', 3, true));
console.log(strpad('333', 3, true));
console.log(strpad('4444', 3, true));

console.log("-----------");

//4 sufixos
console.log(strpad('1', 4, true));
console.log(strpad('22', 4, true));
console.log(strpad('333', 4, true));
console.log(strpad('4444', 4, true));

console.log("-----------");

//Prefixo customizado
console.log(strpad('1', 4, false, 'B'));
console.log(strpad('22', 6, false, 'C'));
console.log(strpad('333', 8, false, 'Y'));
console.log(strpad('4444', 9, false, 'Z'));
    
11.09.2017 / 23:00