leo*_*nel 67 ruby forms ruby-on-rails ruby-on-rails-3
我有这个编辑表格.
但是当我存储诸如1.5的东西时,我想将它显示为1.50.
我怎么能用表单助手呢? <%= f.text_field :cost, :class => 'cost' %>
apn*_*ing 160
你应该使用number_with_precision帮手.见文档.
例:
number_with_precision(1.5, :precision => 2)
=> 1.50
Run Code Online (Sandbox Code Playgroud)
在你内形成帮手:
<%= f.text_field :cost, :class => 'cost', :value => (number_with_precision(f.object.cost, :precision => 2) || 0) %>
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如果你真的想显示一些价格,请使用number_to_currency同一页面的doc(在表单上下文中,我会保留number_with_precision,你不想搞砸钱符号)
gku*_*uan 44
或者,您可以使用格式字符串"%.2f" % 1.5.http://ruby-doc.org/docs/ProgrammingRuby/html/ref_m_kernel.html#Kernel.sprintf
小智 10
为此,我使用number_to_currency格式化程序.由于我在美国,默认设置对我来说很好.
<% price = 45.9999 %>
<price><%= number_to_currency(price)%></price>
=> <price>$45.99</price>
Run Code Online (Sandbox Code Playgroud)
如果默认值不适合您,您也可以传入选项.有关api.rubyonrails.org上可用选项的文档