Hi I have a counter which requires 6 numbers
so this could be
000456 001250 015554
etc
but the problem is i get the number as 456 or 1250 and I then need to convert this to 000456 or 001250.
how would I go about doing this?
Thanks
Dan
Hi I have a counter which requires 6 numbers
so this could be
000456 001250 015554
etc
but the problem is i get the number as 456 or 1250 and I then need to convert this to 000456 or 001250.
how would I go about doing this?
Thanks
Dan
For leading zeros you need to display as a string, so assuming you know that your numbers will never exceed six digits you can do this:
var num = // your number
var output = ("000000" + num).slice(-6);
To allow for larger numbers:
var output = num > 99999 ? num : ("000000" + num).slice(-6);
This is an old function of mine, I think it still works :P
function pad(n, len)
{
s = n.toString();
if (s.length < len)
{
s = ('0000000000' + s).slice(-len);
}
return s;
}
Number.prototype.addZero = function(){
return this.toString().length <= 6 ? ("000000" + this).substr(-6) : this.toString();
}
(486).addZero() //"000486"
To be honest, the easiest method to add zeros is the following in my opinion:
function addZeros(num, len){
while((""+num).length < len) num = "0" + num;
return num.toString();
}
This should do it:
function prependZeros(num){
var str = ("" + num);
return (Array(Math.max(7-str.length, 0)).join("0") + str);
}
Examples:
console.log(prependZeros(0)); //000000
console.log(prependZeros(1)); //000001
console.log(prependZeros(12)); //000012
console.log(prependZeros(123)); //000123
console.log(prependZeros(1234)); //001234
console.log(prependZeros(12345)); //012345
console.log(prependZeros(123456)); //123456
console.log(prependZeros(1234567)); //1234567
here's a function I use to pad numbers with leading 0s:
pad = function(num, length){
num = num.toString();
while (num.length < length){
num = "0" + num;
}
return num;
};