Putting a zero before a number to match a digit

Asked 2 years ago, Updated 2 years ago, 41 views

In JavaScript, I want to create a string that displays a certain number and puts a zero in front of it to match the digits.

For example,

How do I do that?

algorithm javascript

2022-09-21 17:53

2 Answers

//You can do this.
var str = "123";
str = "0000" + str;
str = str.slice(-5);
alert(str);


2022-09-21 17:53

For basic grammar versions that use only repetitive statements and string operations:

var number = 257;
var length = 5;

Convert number=number+"//number to string
var str=""
for(var i=0;i<length-number.length;i++){
  str=str+"0";
}
str=str+number;
console.log(str);

As a way to use Array and join,

function pad(n, width) {
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
}
console.log(pad(5,7));

You can do it like this. If you press the Run button under the code, it will be executed, so try each one.


2022-09-21 17:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.