跳至内容 跳至搜索

Active Model Decimal Type

用于 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
方法
T
包含的模块

常量

BIGDECIMAL_PRECISION = 18
 

实例公共方法

type()

# File activemodel/lib/active_model/type/decimal.rb, line 50
def type
  :decimal
end

type_cast_for_schema(value)

# File activemodel/lib/active_model/type/decimal.rb, line 54
def type_cast_for_schema(value)
  value.to_s.inspect
end