Module: Philiprehberger::MathKit::Round

Defined in:
lib/philiprehberger/math_kit/round.rb

Class Method Summary collapse

Class Method Details

.bankers(value, precision: 0) ⇒ Float

Banker’s rounding (round half to even)

Parameters:

  • value (Numeric)

    the value to round

  • precision (Integer) (defaults to: 0)

    number of decimal places

Returns:

  • (Float)

    the rounded value



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/philiprehberger/math_kit/round.rb', line 12

def bankers(value, precision: 0)
  multiplier = 10**precision
  scaled = value * multiplier

  # Check if exactly at the halfway point
  if halfway?(scaled)
    floored = scaled.floor
    # Round to even
    if floored.even?
      floored.to_f / multiplier
    else
      (floored + 1).to_f / multiplier
    end
  else
    scaled.round.to_f / multiplier
  end
end

.ceiling(value, precision: 0) ⇒ Float

Round up (ceiling)

Parameters:

  • value (Numeric)

    the value to round

  • precision (Integer) (defaults to: 0)

    number of decimal places

Returns:

  • (Float)

    the rounded value



35
36
37
38
# File 'lib/philiprehberger/math_kit/round.rb', line 35

def ceiling(value, precision: 0)
  multiplier = 10**precision
  (value * multiplier).ceil.to_f / multiplier
end

.floor(value, precision: 0) ⇒ Float

Round down (floor)

Parameters:

  • value (Numeric)

    the value to round

  • precision (Integer) (defaults to: 0)

    number of decimal places

Returns:

  • (Float)

    the rounded value



45
46
47
48
# File 'lib/philiprehberger/math_kit/round.rb', line 45

def floor(value, precision: 0)
  multiplier = 10**precision
  (value * multiplier).floor.to_f / multiplier
end

.truncate(value, precision: 0) ⇒ Float

Truncate toward zero

Parameters:

  • value (Numeric)

    the value to truncate

  • precision (Integer) (defaults to: 0)

    number of decimal places

Returns:

  • (Float)

    the truncated value



55
56
57
58
# File 'lib/philiprehberger/math_kit/round.rb', line 55

def truncate(value, precision: 0)
  multiplier = 10**precision
  (value * multiplier).truncate.to_f / multiplier
end