Home > OS >  Why operating with decimals in Rails sometimes returns a integer?
Why operating with decimals in Rails sometimes returns a integer?

Time:12-09

Take this examples:

schema.rb

create_table "articles", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8mb3" do |t|
    t.string   "name"
    t.decimal  "total",                precision: 10, default: "0.0"

article_controller.rb

@article.total = @article.total   (1.1).to_d
@article.total # outputs an integer (1)

Why this happens if both values where decimal?

CodePudding user response:

A solution that I found is to add scale to the field, you can generate a migration:

class ChangeFieldToArticle < ActiveRecord::Migration[5.0]
  def change
    change_column :articles, :total, :decimal, default: 0.0, precision: 10, scale: 2
  end
end

With the scale configured the problems was fixed.

  • Related