Put 00 left into another variable

Asked

Viewed 145 times

0

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

ID 1
ID 2
ID 3

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

001
002
003

Would have to be done via JS or can be done directly via Mysql?

  • 1

    Direct via mysql do so

  • @rray The problem with your answer method is that it wants to put two zeros on the left regardless of the size of the ID, which you suggested to complete with zeros until you get a specific number of digits

  • @bfavaretto had not even noticed that he had for Js :/ should have answered there, although it varies a little, since there seems to limit the string, but overall it should be the same thing.

1 answer

3


In mysql @rray already suggested

/a/126604/3635

It would be something like your case:

SELECT lpad('1', 3, 0)

In Javascript you have this example https://stackoverflow.com/a/20460414/1518921 just make the adjustment to 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'));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.