Active Model Decimal 類型
用於小數、高精確度浮點數數字表示的屬性類型。它註冊在 :decimal
鍵下。
class BagOfCoffee
include ActiveModel::Attributes
attribute :weight, :decimal
end
Numeric
執行個體會轉換成 BigDecimal
執行個體。任何其他物件都會使用它們的 to_d
方法進行強制轉換,空白字串除外,空白字串會強制轉為 nil
。如果沒有定義 to_d
方法,則會使用 to_s
將物件轉換成字串,然後使用 to_d
進行強制轉換。
bag = BagOfCoffee.new
bag.weight = 0.01
bag.weight # => 0.1e-1
bag.weight = "0.01"
bag.weight # => 0.1e-1
bag.weight = ""
bag.weight # => nil
bag.weight = :arbitrary
bag.weight # => nil (the result of `.to_s.to_d`)
Decimal
精度預設值為 18,可以在宣告屬性時自訂
class BagOfCoffee
include ActiveModel::Attributes
attribute :weight, :decimal, precision: 24
end
方法
包含的模組
常量
BIGDECIMAL_PRECISION | = | 18 |
執行個體公開方法
type() 連結
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/type/decimal.rb, line 49 def type :decimal end
type_cast_for_schema(value) 連結
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/type/decimal.rb, line 53 def type_cast_for_schema(value) value.to_s.inspect end