ruby/railsで数値を3桁区切りにする方法

  • 58
    Like
  • 0
    Comment
More than 1 year has passed since last update.

結論

Numeric#to_s(:delimited)を使うと良いよ。

ActionView::Helpers::NumberHelpernumber_with_delimiterメソッドと同じものです(内部で呼ばれてる)が、タイプ数が少ない方が良いですよね。怠惰万歳。

ちなみに、検索するとよく出てくるnumber_to_currencyは通貨表示のためのメソッド(頭に$とか¥とか付く)です。なお、こちらも同じくNumeric#to_s(:currency)で使えます。

Numeric#to_s(:delimited)の使い方

要ActiveSupport

require 'active_support/core_ext/numeric/conversions'

12345678.to_s(:delimited)
 # => 12,345,678
12345678.05.to_s(:delimited)
 # => 12,345,678.05
12345678.to_s(:delimited, delimiter: '.')
 # => 12.345.678
12345678.to_s(:delimited, delimiter: ',')
 # => 12,345,678
12345678.05.to_s(:delimited, separator: ' ')
 # => 12,345,678 05
12345678.05.to_s(:delimited, locale: :fr)
 # => 12 345 678,05
98765432.98.to_s(:delimited, delimiter: ' ', separator: ',')
 # => 98 765 432,98

参考

https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/numeric/conversions.rb#L46-L54

環境情報

OS, Kernel

% inxi -SM
System:    Host: hakuba.vps.sakura.ne.jp Kernel: 2.6.32-279.11.1.el6.x86_64 x86_64 (64 bit)
           Console: tty 5 Distro: CentOS release 6.6 (Final)
Machine:   System: Red Hat product: KVM v: RHEL 6.2.0 PC
           Mobo: N/A model: N/A Bios: Sea v: 0.5.1 date: 01/01/2007

Ruby, Rails

% rake about
About your application's environment
Rails version        4.2.1
Ruby version         2.1.2-p95 (x86_64-linux)
RubyGems version     2.4.4
Rack version         1.5

ActiveSupport

% gem list activesupport
*** LOCAL GEMS ***
activesupport (4.2.1)