【发布时间】:2019-01-04 12:31:27
【问题描述】:
我正在为我的系统中的发票制作 PDF,我希望能够在数据库中存储两位小数的数字。我正在使用MoneyRails gem 来处理货币,我在数据库级别设置了precision: 10 和scale: 2(我使用postgres 作为我的数据库),但逗号后只有一位小数。为什么?
class AddPrecisionToInvoices < ActiveRecord::Migration[5.2]
def self.up
change_column :invoices, :total_net_amount_cents, :decimal, precision: 10, scale: 2, default: 0.00
change_column :invoices, :total_gross_amount_cents, :decimal, precision: 10, scale: 2, default: 0.00
end
def self.down
change_column :invoices, :total_net_amount_cents, :bigint
change_column :invoices, :total_gross_amount_cents, :bigint
end
end
invoice.rb
monetize :total_net_amount_cents
monetize :total_gross_amount_cents
在 Rails 控制台中,
invoice.total_gross_amount_cents = Money.new(20_000_00)
invoice.total_gross_amount.to_f #=> 2000.0
是否可以在 DB 中存储两位小数的数字,例如 20,000.00?
我不想在视图中显示 PDF,因此我希望能够将数字从前端应用程序的参数中获取到我的数据库中,而无需在视图中进一步格式化。
【问题讨论】:
-
您没有存储两位小数的数字。
.是小数,,是千位分隔符。如果您希望将值存储为完全未更改的提交,那么您需要将其存储为字符串。然后,该数据的价值受到更多限制,即不能相加等。 -
我检查了
psql控制台中的值,它保存为1200.00,有两位小数,所以它是正确的。我只需要一种在从 DB 中检索值后正确格式化值的方法,因为money-rails将值转换为 Money 对象。我可以调用value.format来获得一个适合显示但不适合计算的值。我还需要弄清楚这一点。 -
我很抱歉@jedi,我快速阅读了你的两个问题。我假设您希望存储所有格式(例如逗号和句点)。
-
没有问题。我只想保留两位小数。还没找到解决办法。