177
141

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/railsで数値を3桁区切りにする方法

Last updated at Posted at 2015-04-29

結論

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

参考

環境情報

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)
177
141
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
177
141

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?