4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JavaScript】 JSで0埋めして桁数を揃える(ゼロパディング)

Last updated at Posted at 2019-04-24

やりたいこと

複数の数字の桁数を0で埋めて揃えたい

これを

1
2
3
...
98
99
100

こう!!
↓↓↓

001
002
003
...
098
099
100

こうやる

zero_padding.js
const minNumber = 1; // 最小値
const maxNumber = 100; // 最大値
const digitNumber = 3; // 桁数

const ZeroPadding = (number, digit) => {
  const zeros = Array(digit + 1).join(0); // 桁数分の'0'を文字列として生成 => 000
  const zerosJoinNumber = zeros + number; // 000の末尾にnumberを結合 => 0001 〜 000100
  const zeroPaddingNumber = zerosJoinNumber.slice(-digit); // 末尾から桁数分切り出す => 001 〜 100
  return zeroPaddingNumber;
};

// minNumber 〜 maxNumberの間でループ
for (let count = minNumber; count <= maxNumber; count++) {
  const result = ZeroPadding(count, digitNumber);
}

追記

コメントにて@altさんにスマートなやり方を教えて頂きました。
ありがとうございます、勉強になりました!

console.log(...[...Array(100)].map((_, i) => `${i + 1}`.padStart(3, 0)));
4
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?