LoginSignup
0
0

More than 3 years have passed since last update.

JavaScriptで数字の頭に0を加えて桁揃えする

Last updated at Posted at 2019-09-10

練習でタイマーを作るために、
0:0:0となる数字表記を00:00.000と数字の桁を揃えたかったのですが、
ググってもなかなかヒットしなかったので、簡単に記録します。

1.使用するメソッド

String(xx).padStart(2, '0')
そうです。padStart関数です。

2.使用例(カウントアップのための関数)

    function countUp() {
        const d = new Date(Date.now() - startTime + elapsedTime);
        const m = d.getMinutes(); // 分
        const s = d.getSeconds(); // 秒
        const ms = d.getMilliseconds(); // ミリ秒

        // タイマーの表示方法を指定 ★★★ここです★★★
        timer.textContent = `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}.${String(ms).padStart(3, '0')}`;

        // 再帰的な処理
        timeoutId = setTimeout(() => {
            countUp();
        }, 10);

    }
0
0
0

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