Ruby-on-rails Rails 3. 如何在编辑表单中显示两位小数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7772859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails 3. How to display two decimal places in edit form?
提问by leonel
I have this edit form.
我有这个编辑表格。
But when I store something such as 1.5, I would like to display it as 1.50.
但是当我存储诸如 1.5 之类的东西时,我想将其显示为 1.50。
How could I do that with the form helper? <%= f.text_field :cost, :class => 'cost' %>
我怎么能用表单助手做到这一点? <%= f.text_field :cost, :class => 'cost' %>
回答by apneadiving
You should use number_with_precisionhelper. See doc.
你应该使用number_with_precision助手。见文档。
Example:
例子:
number_with_precision(1.5, :precision => 2)
=> 1.50
Within you form helper:
在你的表单助手中:
<%= f.text_field :cost, :class => 'cost', :value => (number_with_precision(f.object.cost, :precision => 2) || 0) %>
BTW, if you really want to display some price, use number_to_currency, same page for doc (In a form context, I'd keep number_with_precision, you don't want to mess up with money symbols)
顺便说一句,如果您真的想显示一些价格,请使用number_to_currencydoc 的同一页面(在表单上下文中,我会保留number_with_precision,您不想弄乱货币符号)
回答by gkuan
Alternatively, you can use the format string "%.2f" % 1.5. http://ruby-doc.org/docs/ProgrammingRuby/html/ref_m_kernel.html#Kernel.sprintf
或者,您可以使用格式字符串"%.2f" % 1.5。http://ruby-doc.org/docs/ProgrammingRuby/html/ref_m_kernel.html#Kernel.sprintf
回答by codesponge
For this I use the number_to_currencyformater. Since I am in the US the defaults work fine for me.
为此,我使用number_to_currency格式化程序。由于我在美国,默认设置对我来说很好。
<% price = 45.9999 %>
<price><%= number_to_currency(price)%></price>
=> <price>.99</price>
You can also pass in options if the defaults don't work for you. Documentation on available options at api.rubyonrails.org
如果默认值不适合您,您还可以传入选项。api.rubyonrails.org上可用选项的文档
回答by Brian
Rails has a number_to_currencyhelper method which might fit you specific use case better.
Rails 有一个number_to_currency辅助方法,它可能更适合您的特定用例。

