Module: UsefulUtilities::Numeric

Extended by:
Numeric
Included in:
Numeric
Defined in:
lib/useful_utilities/numeric.rb

Overview

Numeric utilities

Constant Summary collapse

ZERO =
0
THOUSAND =
1_000
MILLION =
1_000_000
BILLION =
1_000_000_000

Instance Method Summary collapse

Instance Method Details

#float_or_integer(value) ⇒ Numeric

Returns value if value can not be coerced to integer.

Parameters:

Returns:

  • (Numeric)

    value if value can not be coerced to integer



22
23
24
# File 'lib/useful_utilities/numeric.rb', line 22

def float_or_integer(value)
  value == value.to_i ? value.to_i : value
end

#positive_or_zero(value) ⇒ Numeric

Examples:

UsefulUtilities::Numeric.positive_or_zero(1)  #=> 1
UsefulUtilities::Numeric.positive_or_zero(-1) #=> 0

Parameters:

Returns:



16
17
18
# File 'lib/useful_utilities/numeric.rb', line 16

def positive_or_zero(value)
  (value > ZERO) ? value : ZERO
end

#to_decimal(value, scale: nil) ⇒ BigDecimal

Returns value as BigDecimale rounded to scale.

Parameters:

  • value (Numeric)
  • scale (Hash) (defaults to: nil)

    a customizable set of options

Options Hash (scale:):

  • :scale (Integer) — default: nil

Returns:

  • (BigDecimal)

    value as BigDecimale rounded to scale



29
30
31
32
33
# File 'lib/useful_utilities/numeric.rb', line 29

def to_decimal(value, scale: nil)
  result = value.to_f.to_d

  scale ? result.round(scale) : result
end

#to_giga(value, unit) ⇒ Numeric

Returns value converted to giga.

Parameters:

Returns:

  • (Numeric)

    value converted to giga



48
49
50
51
52
53
# File 'lib/useful_utilities/numeric.rb', line 48

def to_giga(value, unit)
  if    unit == :k then value.fdiv(MILLION)
  elsif unit == :M then value.fdiv(THOUSAND)
  else  unsupported_unit!(unit)
  end
end

#to_kilo(value, unit) ⇒ Numeric

Returns value converted to kilo.

Parameters:

Returns:

  • (Numeric)

    value converted to kilo



38
39
40
41
42
43
# File 'lib/useful_utilities/numeric.rb', line 38

def to_kilo(value, unit)
  if    unit == :M then value * THOUSAND
  elsif unit == :G then value * MILLION
  else  unsupported_unit!(unit)
  end
end

#to_number(value, unit) ⇒ Numeric

Returns value converted to number.

Parameters:

Returns:

  • (Numeric)

    value converted to number



59
60
61
62
63
64
# File 'lib/useful_utilities/numeric.rb', line 59

def to_number(value, unit)
  if    unit == :M then value * MILLION
  elsif unit == :G then value * BILLION
  else  unsupported_unit!(unit)
  end
end