Module: Mayak::Numeric

Extended by:
T::Sig
Defined in:
lib/mayak/numeric.rb

Class Method Summary collapse

Class Method Details

.parse_decimal(value) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/mayak/numeric.rb', line 29

def self.parse_decimal(value)
  return Mayak::Monads::Maybe::None[BigDecimal].new if value.nil?

  case value
  when String
    Mayak::Monads::Maybe::Some[BigDecimal].new(BigDecimal(value))
  when Integer
    Mayak::Monads::Maybe::Some[BigDecimal].new(BigDecimal(value))
  when BigDecimal
    Mayak::Monads::Maybe::Some[BigDecimal].new(value)
  when Float
    Mayak::Monads::Maybe::Some[BigDecimal].new(BigDecimal(value, Float::DIG + 1))
  end
rescue ArgumentError, TypeError
  Mayak::Monads::Maybe::None[BigDecimal].new
end

.parse_float(value) ⇒ Object



11
12
13
14
15
16
17
# File 'lib/mayak/numeric.rb', line 11

def self.parse_float(value)
  return Mayak::Monads::Maybe::None[Float].new if value.nil?

  Mayak::Monads::Maybe::Some[Float].new(Float(value))
rescue ArgumentError, TypeError, FloatDomainError
  Mayak::Monads::Maybe::None[Float].new
end

.parse_integer(value) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/mayak/numeric.rb', line 20

def self.parse_integer(value)
  return Mayak::Monads::Maybe::None[Integer].new if value.nil?

  Mayak::Monads::Maybe::Some[Integer].new(Integer(value))
rescue ArgumentError, TypeError
  Mayak::Monads::Maybe::None[Integer].new
end

.percent_of(value:, total:) ⇒ Object



47
48
49
50
51
# File 'lib/mayak/numeric.rb', line 47

def self.percent_of(value:, total:)
  return BigDecimal(0) if total.zero?

  value / total * BigDecimal(100)
end