0

我正在为我的系统中的发票制作 PDF,我希望能够在数据库中存储两位小数的数字。我正在使用MoneyRailsgem 来处理货币,我已经设置precision: 10scale: 2在数据库级别(我postgres用作我的数据库),但我在逗号后只得到 1 个小数位。为什么?

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

发票.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,因此我希望能够将数字放入我的数据库中,因为我从前端应用程序的参数中获取它,而无需在视图中进一步格式化它。

4

2 回答 2

0

money-rails gem 要求monetize数据库中的列是数字。但是,它附带了一些帮助方法,您可以使用这些方法在模型中根据需要重新格式化:

# inside Invoice model
require "money-rails/helpers/action_view_extension"
class Invoice < ApplicationRecord
  include MoneyRails::ActionViewExtension
  # ...
  def total_gross_amount_formatted
    humanized_money total_gross_amount
  end
end

然后在您的 PDF 中,您可以引用新的格式化属性:

@invoice_instance.total_gross_amount_formatted
于 2019-01-04T13:41:04.187 回答
0

您可以尝试以下,(在模型中使用)

ActiveSupport::NumberHelper::number_to_delimited('%.2f' % '3423432.43234', delimiter: ",", separator: ".")

# => "3,423,432.43"

在这里,在上面的输入3423432.43234中以字符串形式提供,您也可以将其作为数字提供。

可以直接number_with_delimiter在视图中使用

于 2019-01-04T12:39:04.473 回答