Rails 3. 如何在模型中显式地将数字四舍五入到小数点后两位? [英] Rails 3. How to explicitly round a number to two decimal places in the model?

查看:38
本文介绍了Rails 3. 如何在模型中显式地将数字四舍五入到小数点后两位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Rails 3. 如何在中显示两位小数编辑表单?

我知道我可以使用 sprintf 来限制小数点后两位.

I know I can use sprintf to limit to two decimal places.

当我以表格形式或仅在表格中重新显示价格时,有时我会得到 80,而不是 80.00.从价格输入数据库的那一刻起,只存储两位小数的价格不是更好吗?这样,无论何时显示,它都会显示小数点后两位.如果是这样,如何?

When I redisplay the prices in a form or just in a table, sometimes I get 80, instead of 80.00. Wouldn't be better to just store the price with the two decimal places from the very moment the price is entered in the database? That way, whenever it's displayed, it will ALWAYS show the two decimal places. If so, how?

推荐答案

您应该尝试使用 :decimal 类型的数据库字段,并将 :scale 设置为 <代码>2

You should try using the :decimal type of database field, with the :scale set to 2

向新表中添加小数列;

create_table :my_table do |t|
  t.decimal :my_column, :scale => 2
end

向现有表中添加一列;

add_column :my_table, :my_column, :decimal, :scale => 2

拥有精度是明智的,因为某些数据库没有精度默认值.比如postgresql:

It is wise to have precisions since some database does not have precision defaults. Such as postgresql:

 add_column :my_table, my_column, precision: 30, scale: 2

这篇关于Rails 3. 如何在模型中显式地将数字四舍五入到小数点后两位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆