# 開発時によく使うゼロ埋めパディング作業まとめ

int 数字を左からゼロ埋めする時ありません?いちいちぐぐってません?よく忘れるので、まとめました。

ゼロ埋めの芸名はゼロパディングである

# php でゼロ埋め

str_pad (opens new window) 使う

echo str_pad(5, 2, 0, STR_PAD_LEFT); // 05
echo str_pad(23, 3, 0, STR_PAD_LEFT); // 023

sprintf (opens new window) 使う

echo sprintf('%02d', 3); // 03
echo sprintf('%03d', 12); // 012
echo sprintf('ID番号 %04d', 99); // ID番号 0099

# ゼロ埋め twig バージョン

format filter (opens new window) 使う

{{ '%04d'|format(u.id) }}

# ゼロ埋め mysql バージョン

LPAD (opens new window)使う

SELECT LPAD(`id`, 4, '0') FROM `user`;

結果

LPAD(id, 4, '0')
001
002
003

# ゼロ埋め javascript バージョン

javascript で手軽にゼロ埋めパディングすることもできます!

slice (opens new window) 使う

const num = 5;
const str = ("000" + num).slice(-3);
console.log(str);
// 005

padStart (opens new window) 使う

const str1 = "3";
console.log(str1.padStart(2, "0"));
// 03

function で書いてみる

function zeroPadding(num, length) {
  return ("0000" + num).slice(-length);
}

const num = zeroPadding(123, 6);
console.log(num); // 000123

function leftFillNum(num, targetLength) {
  return num.toString().padStart(targetLength, 0);
}

const num = 123;
console.log(leftFillNum(num, 5));
// 00123

# おまけ:vue filter ナンバーフォーマットなど

import Vue from "vue";

function zeroPadding(num, length) {
  return ("0000" + num).slice(-length);
}

function numberFormat(num) {
  return (num || 0)
    .toString()
    .replace(/^-?\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+$)/g, ","));
}

function moneyFormat(num) {
  return (
    "¥" +
    (num || 0)
      .toString()
      .replace(/^-?\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+$)/g, ","))
  );
}

function uppercaseFirst(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

Vue.filter("number", numberFormat);
Vue.filter("money", moneyFormat);
Vue.filter("upperFirst", uppercaseFirst);
2020-07-15

同じタグを持つ記事をピックアップしました。