LoginSignup
1
0

More than 3 years have passed since last update.

JavaScriptで数値を任意の文字数のゼロ埋め文字列にする

Posted at

結論

数値のゼロ埋め(zfill, ゼロフィル)にはpadStart()を使いましょう。

本題

「JavaScript zfill」とかで検索しても、'000' + String(num)みたいに文字列をくっつけてからslice()するみたいな手法がたくさん引っかかりますが、今のJavaScriptにはpadStart()という便利な関数がありました。


const num = 123;
console.log(String(num).padStart(5, '0') // '00123'

使い方

冒頭のリファレンス読めばわかりますが以下のとおりです

String.prototype.padStart(<目標の文字数>, <目標への不足分を埋める文字>)

1
0
1

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
1
0