【问题标题】:Why decimal holding value like 0.219e3 instead of 219.0 which I want为什么十进制保持值像 0.219e3 而不是我想要的 219.0
【发布时间】:2019-08-14 21:00:25
【问题描述】:

我正在使用 Ubuntu 18.04.2 LTS 和 ruby​​ 2.5.1p57 和 rails 5.2.3

我有这样的模型:

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

在我的种子中,我正在尝试为我的数据库播种:

 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   
}

当我在数据库中调用 rails db:seed 时,我可以看到这样的 CreatePriceList 对象:

#<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">

我正在寻找如何在数据库中存储价格/货币/货币的示例,所有示例都说我必须使用decimal

所以,现在我将列类型更改为 float,一切正常,但如果这是最好的选择,我想更改为 decimal,但需要知道发生了什么。

【问题讨论】:

  • 你使用的是什么数据库服务器?
  • 默认一个,sqlite3
  • sqlite3 没有十进制数据类型。这可以解释你的问题。如果您要存储钱,那么存储为整数并乘以 100 怎么样。例如:以美分存储数字。
  • @Rots by 100?在日本、阿曼、卡塔尔不行……

标签: ruby-on-rails ruby decimal currency


【解决方案1】:

当列类型为 Decimal 时,适配器可能会将值转换为 ruby​​ 上的 BigDecimal 对象。

require 'bigdecimal'

BigDecimal(219)
=> 0.219e3

这个数字实际上是“219”,只是科学记数法(0.219 x 10^3)。

BigDecimal(219) == 219
=> true

BigDecimal(219).to_f
=> 219.0

【讨论】:

    猜你喜欢
    • 2014-10-27
    • 2019-04-11
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多