7777777.to_s.rjust(3, '0').gsub(/(\d{2})$/, '.\1').gsub( /(^|\s)(\d+)(\d{2})/ ){|x| x.gsub(/(?=(?!\b)(\d{3})+$)/, ',')}
也可以在非 view 的地方使用
ActionController::Base.helpers.number_to_currency 7777777
rubymoney,也考虑用过,最后花了点时间,给 number_to_currency 加了一层来处理。
本着能不用 gem 尽量不用的原则。各项配置能入库一律入库。
currencies 和 number_to_currency 的各项参数,每一种货币的配置写入数据库。
增加了一个 cents 参数:
1 单位的货币 = 多少 cents,
积分的话:1 unit = 1cents
人民币:1 unit = 100 cents
最后配合:precision 参数,基本没差别了
def money(credit, currency)
number_to_currency(
credit*1.0/currency.cents, unit: currency.unit,
delimiter: currency.delimiter, separator: currency.separator, precision: currency.precision,
format: currency.format,
)
end
# or
def money(credit, currency)
number_to_currency( credit*1.0/currency.cents, currency.attributes )
end
# use helper
2.3.3 (main):0 > helper.number_to_currency 7777777
=> "¥ 7,777,777.00"
# active_support
2.3.3 (main):0 > 7777777.to_s(:currency)
=> "¥ 7,777,777.00"
# include precision
2.3.3 (main):0 > 7777777.to_s(:currency, precision: 3)
=> "¥ 7,777,777.000"
这种方法文档直接搜搜不到,看来只能从源码入手了 NumericWithFormat http://api.rubyonrails.org https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/numeric/conversions.rb