38
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rubyで数値を3桁区切りにする方法!

Last updated at Posted at 2019-06-20

フリマアプリなどを開発していく中で、商品の値段を3桁で区切って表示させたい時とかありますよね!

例) 「1,000円」といったように...

そんな時に活躍するのが、:delimitedメソッドです!

delimitedメソッド

sample.rb
12345678.to_s(:delimited)
 # => 12,345,678
12345678.05.to_s(:delimited)
 # => 12,345,678.05

:delimiterオプションを利用することで、桁区切り文字も指定することができます!

sample.rb
12345678.to_s(:delimited, delimiter: '.')
 # => 12.345.678
12345678.to_s(:delimited, delimiter: ',')
 # => 12,345,678

メソッドを活用した例をみていきましょう!

「1000」という数値が引数で与えられたら「1,000円」といったように、「桁区切り」と「円」を追加する、ヘルパーメソッドconverting_to_jpyを定義します!

app/helpers/product_helper.rb
module ProductsHelper
  def number_to_currency(price)
    "#{price.to_s(:delimited, delimiter: ',')}円"
  end
end

完成です!


delimitedメソッドは他にもオプションがあるので、興味が湧いた方は是非調べてみてください!

ご静聴ありがとうございました:relaxed:

https://railsguides.jp/active_support_core_extensions.html#%E6%9B%B8%E5%BC%8F%E8%A8%AD%E5%AE%9A

38
43
6

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
38
43

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?