LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby on Rails】数値の0埋めをする方法

Last updated at Posted at 2023-01-29

前提条件

  • Ruby 3.1.0
  • Rails 7.0.4

やりたいこと

出力値を8桁固定にし、頭は0埋めで表示する。
(例)

現状の出力値 理想の出力値
1234 00001234
12345 00012345
123456 00123456

方法

Formatメソッドを使う

書き方
format("%<桁数>d", <出力する数値>)

今回は桁数が8桁、出力する数値が1234なので以下のようになる。

実装
format("%08d", 1234)
# => "00001234"

他の例も同様である。

実装
format("%08d", 12345)
# => "00012345"
実装
format("%08d", 123456)
# => "00123456"

参考

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