Rails 中货币格式化的简单方法

Dot*_*tol 6 ruby currency ruby-on-rails

我今天大部分时间都在尝试弄清楚如何为我的整数字段提供货币格式,并受到无数不同方法的轰炸,从使用 Money、Rails-Money gems 到使用自定义帮助器方法或语言环境。

\n\n
\n

您可以使用该number_to_currency方法来实现此目的。假设您有以下视图:

\n
\n\n

视图.html.erb

\n\n
<ul>\n    <li><%= client.payment %></li>\n</ul>\n
Run Code Online (Sandbox Code Playgroud)\n\n

假设列 payment 的类型为整数,这将打印出一个没有格式的数字。例如:5523

\n\n
\n

现在添加 number_to_currency 方法并指定您想要使用的货币单位(可以是任意)

\n
\n\n
<ul>\n    <li><%= number_to_currency(client.payment, :unit => "$") %></li>\n</ul>\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在我们得到这样的结果:5.523.00$

\n\n
\n

number_to_currency 方法助手默认有一些选项,其中一个是反转(与常见做法相反)逗号和句点的使用。可以通过添加选项\n :separator 和 :delimiter 来修改它们,并为它们提供您想要的值,\n 如下所示。

\n
\n\n
<ul>\n    <li><%= number_to_currency(client.payment, :unit => "$", :separator => ".", :delimiter => ",") %></li>\n</ul>\n
Run Code Online (Sandbox Code Playgroud)\n\n

这些是 number_to_currency 方法帮助器 ( RubyOnRailsAPI )的可用选项:

\n\n
:locale - Sets the locale to be used for formatting (defaults to current locale).\n\n:precision - Sets the level of precision (defaults to 2).\n\n:unit - Sets the denomination of the currency (defaults to \xe2\x80\x9c$\xe2\x80\x9d).\n\n:separator - Sets the separator between the units (defaults to \xe2\x80\x9c.\xe2\x80\x9d).\n\n:delimiter - Sets the thousands delimiter (defaults to \xe2\x80\x9c,\xe2\x80\x9d).\n\n:format - Sets the format for non-negative numbers (defaults to \xe2\x80\x9c%u%n\xe2\x80\x9d). Fields are %u for the currency, and %n for the number.\n\n:negative_format - Sets the format for negative numbers (defaults to prepending a hyphen to the formatted number given by :format). Accepts the same fields than :format, except %n is here the absolute value of the number.\n\n:raise - If true, raises InvalidNumberError when the argument is invalid.\n
Run Code Online (Sandbox Code Playgroud)\n

jdg*_*ray 5

您可以通过几种不同的方式来做到这一点。就我个人而言,我建议在装饰器(https://github.com/drarapgem/draper)中执行此操作,以从视图中删除一些逻辑和格式。

正如前面的答案中提到的,您可以使用number_to_currency或不使用其他选项来获得您正在寻找的正确格式。它可以采用整数、浮点数或字符串。

number_to_currency 10000
=> "$10,000.00"
Run Code Online (Sandbox Code Playgroud)

如果你想处理一个对象,另一种方法是使用money-railshttps://github.com/RubyMoney/money-railsMoney ) :

money = Money.new(10000)
=> #<Money fractional:10000 currency:USD>

humanized_money_with_symbol money
=> "$10,000.00"
Run Code Online (Sandbox Code Playgroud)


Hoo*_*nta 0

您是否尝试过在没有任何选项的情况下使用它?
number_to_currency(client. payment)
它应该默认为 $ 并且在没有任何选项的情况下对我来说工作得很好。