number_with_delimiter (数値をカンマ区切りで出力)

2012年11月26日

Ruby on Railsで数値を整形する場合、ActionViewには便利なヘルパーがあります。

number_with_delimiter
です。

[ruby]
number_with_delimiter(12345678) # => 12,345,678
number_with_delimiter("123456") # => 123,456
number_with_delimiter(12345678.05) # => 12,345,678.05
number_with_delimiter(12345678, :delimiter => ".") # => 12.345.678
number_with_delimiter(12345678, :delimiter => ",") # => 12,345,678
number_with_delimiter(12345678.05, :separator => " ") # => 12,345,678 05
number_with_delimiter(12345678.05, :locale => :fr) # => 12 345 678,05
number_with_delimiter("112a") # => 112a
number_with_delimiter(98765432.98, :delimiter => " ", :separator => ",")
# => 98 765 432,98

number_with_delimiter("112a", :raise => true) # => raise InvalidNumberError
[/ruby]

Ruby on Rails メモ

Posted by GENDOSU