class Bytepack::Decimal
Constants
- DIRECTIVE
- LENGTH
- NULL_INDICATOR
- PRECISION
- SCALE
Public Class Methods
deserialize(val, offset = 0)
click to toggle source
# File lib/bytepack/basic/fixed_size/decimal.rb, line 37 def deserialize(val, offset = 0) unscaled = bytesToInt(self::LENGTH, val, offset) if unscaled != self::NULL_INDICATOR unscaled = unscaled.to_s scaled = unscaled.insert(unscaled.size - self::SCALE, ".") BigDecimal(scaled) end end
pack(val)
click to toggle source
# File lib/bytepack/basic/fixed_size/decimal.rb, line 13 def pack(val) (val == self::NULL_INDICATOR || val.nil?) ? intToBytes(self::LENGTH, self::NULL_INDICATOR) : serialize(val) end
serialize(val)
click to toggle source
# File lib/bytepack/basic/fixed_size/decimal.rb, line 21 def serialize(val) num = case val when BigDecimal then val else val.to_d end sign, digits, base, exponent = *num.split scale = digits.size - exponent precision = digits.size raise(::ArgumentError, "Scale of this decimal is #{scale} and the max is #{self::SCALE}") if scale > self::SCALE rest = precision - scale raise(::ArgumentError, "Precision to the left of the decimal point is #{rest} and the max is #{self::PRECISION-self::SCALE}") if rest > 26 scale_factor = self::SCALE - scale unscaled_int = sign * digits.to_i * base ** scale_factor # Unscaled integer intToBytes(self::LENGTH, unscaled_int) end
unpack(bytes, offset = 0)
click to toggle source
# File lib/bytepack/basic/fixed_size/decimal.rb, line 17 def unpack(bytes, offset = 0) [deserialize(bytes, offset), offset + self::LENGTH] end