I want my output as 0000, 0001, 0002. If i use normal js math then the result come 0,1,2
var count=0000+1;
document.write(count);
Output is 1
But i want output as 0001
how to do this?
I want my output as 0000, 0001, 0002. If i use normal js math then the result come 0,1,2
var count=0000+1;
document.write(count);
Output is 1
But i want output as 0001
how to do this?
The +
operator in Javascript is used for both addition and concatenating depending on the operands. 0000+1
is just adding zero and one, which gives one. You can concatenate the string "000"
to the number 1
and it will give you the string "0001"
, which is what you're looking for.
Here's a function that will always have 4 digits, with leading zeros. It works by concatenating the string "000"
and your number, then shortening, if needed, to 4 characters.
function pad(n) {
var s = "000" + n;
return s.substr(s.length-4);
}
You can use lodash's padStart
You can use it like:
var count = 1;
_.padStart(count, 4, '0');
//this will give you 0001
_.padStart(23, 4, '0');
//this will give you 0023
Use:
var count = 1;
document.write( '0000'.substr( String(count).length ) + count );
This is not possible using integer, but you can do something like,
"000"+1
output => "0001"
P.S: Maybe if you share your use case, I can help you better.
Add the zeros and then remove the ones that are left over:
function renameArtboards(){
var docRef = app.activeDocument;
var aB = docRef.artboards;
for(var a=0;a<aB.length;a++){
var curAB = aB[a];
var sNumber = "000" + [a+1];
curAB.name = sNumber.substr(sNumber.length-4);
}
}
renameArtboards();
I know I'm an year and a half late but I happen to need this kind of logic in my app right now. The most "elegant" solution in my opinion is this one:
const yourNumber = 32;
const defaultFill = "0000"
const formattedNumber = (defaultFill + yourNumber).substr(String(yourNumber).length)
This one works just fine for my use-case. It may have some limits if you have to handle numbers with more than 4 digits – in that case you could lose some information on the way. Be aware of that.
I hope this helped you, cheers!
var JobNumber = 'JB-00000';
var digistextraction = JobNumber.substr(3,5);
var JobNumberTable=[];
for (var j = 0; j < 5; j++) {
k=1;
digistextraction = parseInt(digistextraction) + k;
JobNumberTable.push('JB-' + digistextraction.toLocaleString(undefined, {useGrouping: false, minimumIntegerDigits: 5}));
k++;
}
console.log(JobNumberTable);
Best way is
var NumberWithLeadingZeroes = "000" + 1;
alert(NumberWithLeadingZeroes);//Will give you "0001"
UPDATE
function NumberWithLeadingZeroes (n)
{
if ( n< 10 )
{
return ( '000' + n.toString () );
}
else if ( n< 100 )
{
return ( '00' + n.toString () );
}
else if ( n< 1000 )
{
return ( '0' + n.toString () );
}
else
{
return ( n);
}
}