Module: Philiprehberger::MathKit::Round
- Defined in:
- lib/philiprehberger/math_kit/round.rb
Class Method Summary collapse
-
.bankers(value, precision: 0) ⇒ Float
Banker’s rounding (round half to even).
-
.ceiling(value, precision: 0) ⇒ Float
Round up (ceiling).
-
.floor(value, precision: 0) ⇒ Float
Round down (floor).
-
.truncate(value, precision: 0) ⇒ Float
Truncate toward zero.
Class Method Details
.bankers(value, precision: 0) ⇒ Float
Banker’s rounding (round half to even)
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)
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)
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
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 |