【问题标题】:number_to_human with currencynumber_to_human 与货币
【发布时间】:2013-04-02 18:23:48
【问题描述】:
我正在使用 number_to_human 打印 400 万。我想知道是否有一种方法可以将 $ 添加到数字的前面?
当我有一个负数时,我会遇到问题。
如果我只是在前面扔一个美元,我会得到他们想要的 -400 万美元 -400 万美元
【问题讨论】:
标签:
ruby-on-rails
ruby-on-rails-3
rubygems
ruby-on-rails-3.2
【解决方案1】:
它是内置的 Rails:
number_to_currency(number_to_human(-4000000))
# => "-$4 Million"
使用约定的最大优势在于,当您需要 i18n 时,您只需传递语言环境:
number_to_currency(number_to_human(-4000000), locale: 'en-EU')
# => "-4 Million €"
【解决方案2】:
它很有趣,如果它对任何人都有帮助:
How to Present thousands as "K", millions as "M" in ruby for that,
just follow the steps
在顶部的控制器中包含 NumberHelper
include ActionView::Helpers::NumberHelper
使用这个 number_to_human Helper 并传递值,这将转换值
<%= number_to_human(5223654) %>
将此代码粘贴到 en.yml 中以使其正常工作
en:
number:
human:
decimal_units:
format: "%n%u"
units:
unit: ""
thousand: K
million: M
billion: B
trillion: T
quadrillion: Q
【解决方案3】:
一定有更好的方法。但是,这里有一个快速破解
amount = -4000000
if amount < 0
human = "-$#{number_to_human(amount.abs)}"
else
human = "$#{number_to_human(amount)}"
end
@apneadiving 展示了真正简单的方法。