2017.4.3
2017.4.17

数値を3桁区切りの文字列に変換する

数値や金額を画面上に表示する際、桁が多いとただ表示しただけでは大変見にくいので、大抵の場合、3桁ごとにカンマを挿入した形で表示したくなります。

Rubyでどうやるのかと思って調べたら、意外に簡単でした。

目次

  • active_supportのインストール
  • コード
  • 参考リンク

active_supportのインストール

まず、active_supportが必要なので入っていなければ下記のコマンドを実行してインストールします。

gem install activesupport

コード


require 'active_support/core_ext'

#  Delimited:
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"

自分の環境では、「locale」での指定で以下のようなエラーが出ました。

I18n::InvalidLocale - :fr is not a valid locale

localeを指定する場合、国際化の対応が必要みたいです。

参考リンク

Ruby】関連記事