LoginSignup
18
12

More than 5 years have passed since last update.

javascriptで数字を2桁で表示する方法

Last updated at Posted at 2017-01-04

時刻表示に時に少し詰まったのでメモ

1 => 01
0 => 00

みたいな感じ

数字を常に2桁で表示にする関数

getdoubleDigestNumer(number) {
  return ("0" + number).slice(-2)
}

String.prototype.slice()を使ったらすごいシンプルにかけた。
最初は↓のような関数を定義してました...

const getdoubleSecond = (second) => {
  if (second < 10) {
    const {doubleSecond} = '0' + {second}
    return {doubleSecond}
  } else {
    return {second}
  }
}

String.prototype.slice()

String.prototype.slice()は文字列の一部を取りだしてくれるメソッドで

1つ目の引数は取り出す文字列の始点
2つ目は終点です。
ただし、二つとも0から始まるインデックスです。

var numer = "123456789"

//4文字目からを取り出す
numer.slice(3)
=> "456789"

// 下3文字目から取り出す
numer.slice(-3)
=> "789"

// 3文字目まで取り出す
numer.slice(0,3)
"123"

// 下三文字目まで取り出す
numer.slice(0,-3)
"123456"

// 2文字目から7文字目まで取り出す
numer.slice(2,7)
"34567"

すごい便利ですね。
果たして「下○文字目」という日本語はあるのろうか(数字でいいう「
下○桁」という意味です。)

参考

18
12
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
18
12