반응형

고정 길이의 문자열이 되도록 숫자 앞에 0을 추가하는 방법이 있습니까? 

예를 들어 2자리를 지정하면 5는 "05"가 됩니다.

 

 

Small one-liner function using the ES2017 String.prototype.padStart method:

const zeroPad = (num, places) => String(num).padStart(places, '0')

console.log(zeroPad(5, 2)); // "05"
console.log(zeroPad(5, 4)); // "0005"
console.log(zeroPad(5, 6)); // "000005"
console.log(zeroPad(1234, 2)); // "1234"

Another ES5 approach:


function zeroPad(num, places) {
  var zero = places - num.toString().length + 1;
  return Array(+(zero > 0 && zero)).join("0") + num;
}

zeroPad(5, 2); // "05"
zeroPad(5, 4); // "0005"
zeroPad(5, 6); // "000005"
zeroPad(1234, 2); // "1234" :)

 

https://stackoverflow.com/questions/2998784/how-to-output-numbers-with-leading-zeros-in-javascript

 

How to output numbers with leading zeros in JavaScript?

Is there a way to prepend leading zeros to numbers so that it results in a string of fixed length? For example, 5 becomes "05" if I specify 2 places.

stackoverflow.com

 

반응형

+ Recent posts