gpt4 book ai didi

ruby-on-rails - Rails 中货币格式的简单方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:07:00 25 4
gpt4 key购买 nike

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

You can achieve this by using the number_to_currency method. Say you have the following view:

view.html.erb

<ul>
<li><%= client.payment %></li>
</ul>

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

Now add the number_to_currency method and specify which currency unit you'd like to use (can be any)

<ul>
<li><%= number_to_currency(client.payment, :unit => "$") %></li>
</ul>

现在我们得到这样的东西:5.523.00$

The number_to_currency method helper has some options by default, one of those is that it inverts (as opposed to common practice) the usage of comma and period. These can be modified by adding the options :separator and :delimiter and give them the values you'd like as is below.

<ul>
<li><%= number_to_currency(client.payment, :unit => "$", :separator => ".", :delimiter => ",") %></li>
</ul>

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

:locale - Sets the locale to be used for formatting (defaults to current locale).

:precision - Sets the level of precision (defaults to 2).

:unit - Sets the denomination of the currency (defaults to “$”).

:separator - Sets the separator between the units (defaults to “.”).

:delimiter - Sets the thousands delimiter (defaults to “,”).

:format - Sets the format for non-negative numbers (defaults to “%u%n”). Fields are %u for the currency, and %n for the number.

: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.

:raise - If true, raises InvalidNumberError when the argument is invalid.

最佳答案

您可以通过几种不同的方式来实现。我个人建议在装饰器 ( https://github.com/drapergem/draper ) 中执行此操作以从 View 中删除一些逻辑和格式。

如之前的回答所述,您可以使用 number_to_currency 而不是使用其他选项来获得您正在寻找的正确格式。它可以采用整数、 float 或字符串。

number_to_currency 10000
=> "$10,000.00"

另一种方法是使用 money-rails ( https://github.com/RubyMoney/money-rails ) 如果你想处理一个 Money 对象:

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

humanized_money_with_symbol money
=> "$10,000.00"

关于ruby-on-rails - Rails 中货币格式的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43837500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com