Thursday, August 11, 2022

[FIXED] Why decimal holding value like 0.219e3 instead of 219.0 which I want

Issue

I am using Ubuntu 18.04.2 LTS and ruby 2.5.1p57 and rails 5.2.3

I have model like:

class CreatePriceLists < ActiveRecord::Migration[5.2]
  def change
    create_table :price_lists do |t|
      t.integer :number_of_pallets
      t.decimal :net_rabate, precision: 5, scale: 2
      t.decimal :net_logistic, precision: 5, scale: 2

      t.timestamps
    end
  end
end

and in my seeds I am trying to seed my database with :

 CreatePriceLists.create([
{
    number_of_pallets: 2,
    net_rabate: 23.00,
    net_logistic: 25.00
}, {
    number_of_pallets: 5,
    net_rabate: 21.00,
    net_logistic: 35.00   
}

and when I am calling rails db:seed in database I can see CreatePriceList objects like this:

#<CreatePriceLists id: 10, number_of_pallets: 2 net_rabate: 0.209e3, net_logistic: 0.29e3, created_at: "2019-08-14 20:36:50", updated_at: "2019-08-14 20:36:50">

I was looking for examples how to store price/money/currency in database and all examples saying that I have to use decimal

So, right now I change column type to float and everything works like it should, but I would like to change to decimal if that is the best option, but need to know what is going on.


Solution

When the column type is Decimal, the adapter is probably converting the value to a BigDecimal object on ruby.

require 'bigdecimal'

BigDecimal(219)
=> 0.219e3

The number is actually "219", it's just cientific notation (0.219 x 10^3).

BigDecimal(219) == 219
=> true

BigDecimal(219).to_f
=> 219.0


Answered By - arieljuod
Answer Checked By - Katrina (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.