无法在 Rails 3 的文本字段中显示小数
困惑的 Rails 3 新手。我的模型有一个如下定义的 buy_price 属性:
t.decimal :purchase_price, :precision => 12, :scale => 2, :default => 0.00
我的目标是拥有一个简单的 Rails 3 应用程序,我可以在其中查看和编辑该值。在我的模型中,我定义了一个自定义 getter 来强制始终存在 2 位小数。
def purchase_price
sprintf( "%.2f",attributes['purchase_price'])
end
当我显示显示页面时,这可以在控制台中正常工作。在编辑页面上,我有一个文本字段来编辑该值。我的问题是,如果将此值保存为“123.00”,则该值将显示为“123.0”。
问题:
- 为什么我的自定义 getter 没有被调用?
- 为什么显示为 1 位小数而不是 2 位小数?
更新
- MySQL 中存储的十进制值:100.20
- 从控制台返回的值:100.20
- 在文本字段中显示的值:100.2
- 通过 Firebug 返回的值:“100.2”
- 文本字段长度不是问题。
- 如果db中的值为100.21,则正确显示为100.21
Confused Rails 3 newbie. My model has a purchase_price attribute defined like this:
t.decimal :purchase_price, :precision => 12, :scale => 2, :default => 0.00
My goal is to have a simple Rails 3 app where I can view and edit this value. In my model, I defined a custom getter to force 2 decimal places to always exist.
def purchase_price
sprintf( "%.2f",attributes['purchase_price'])
end
This works correctly from the console and when I display the show page. On the edit page I have a text field to edit this value. My problem is that if this value is saved as '123.00' the value is displayed as '123.0'.
Questions:
- Why is my custom getter not getting called?
- Why is this displayed with 1 decimal and not 2 decimals?
Update
- Decimal value as stored in MySQL: 100.20
- Value returned from console: 100.20
- Value displayed in text field: 100.2
- Value returned via Firebug: "100.2"
- The text field length is not an issue.
- If the value in the db is 100.21, it is displayed correctly as 100.21
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个
,这应该将数字转换为货币(有两位小数),并且
:unit=>''
将排除“$”。我建议删除您的自定义
purchase_price
方法,并在需要时使用number_to_currency
帮助程序。覆盖purchase_price
访问器并不是一个坏主意,但它可能会混淆一些可能需要数字而不是字符串的东西。Try this
That should convert the number to a currency (with two decimal places) and the
:unit=>''
will exclude the "$".And I'd recommend removing your custom
purchase_price
method and using thenumber_to_currency
helper where needed instead. Overriding thepurchase_price
accessor isn't a bad idea but it could confuse some things that might be expecting a number rather than a string.