Rails store numbers with 2 decimal places after comma in database

1.7k views Asked by At

I am doing PDFs for invoices in my system and I would like to be able to store numbers with two decimal places in the database. I am using MoneyRails gem for dealing with currencies, I have setup precision: 10 and scale: 2 on the database level (I use postgres as my DB) but I am getting only 1 decimal place after comma. Why?

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

In rails console,

invoice.total_gross_amount_cents = Money.new(20_000_00)
invoice.total_gross_amount.to_f #=> 2000.0

Is it possible to store numbers with two decimal places in DB, like 20,000.00? I don't want to display the PDF in a view so I want to be able to drop the number into my DB as I got it from params from my front-end application without further formatting it in a view.

2

There are 2 answers

9
ray On

You can try following, (using in model)

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

# => "3,423,432.43"

Here, in above input 3423432.43234 is provided as string, you can provide it as number also.

You can directly use number_with_delimiter in view

0
codenamev On

The money-rails gem requires monetize columns to be numeric in the database. However, it comes with some helper methods that you could use to re-format as you wish in your model:

# 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

Then in your PDF you can just reference the new formatted attribute:

@invoice_instance.total_gross_amount_formatted