Module: UmbrellioUtils::Rounding
Constant Summary collapse
- SUPER_ROUND_DEFAULT_TARGETS =
[1.0, 1.5, 2.5, 5.0, 10.0].freeze
Instance Method Summary collapse
- #fancy_round(number, rounding_method: :round, ugliness_level: 1) ⇒ Object
- #super_round(number, rounding_method: :round, targets: SUPER_ROUND_DEFAULT_TARGETS) ⇒ Object
Instance Method Details
#fancy_round(number, rounding_method: :round, ugliness_level: 1) ⇒ Object
9 10 11 12 13 14 |
# File 'lib/umbrellio_utils/rounding.rb', line 9 def fancy_round(number, rounding_method: :round, ugliness_level: 1) return 0 unless number.positive? log = Math.log(number, 10).floor coef = 2**ugliness_level (number * coef).public_send(rounding_method, -log) / coef.to_f end |
#super_round(number, rounding_method: :round, targets: SUPER_ROUND_DEFAULT_TARGETS) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/umbrellio_utils/rounding.rb', line 16 def super_round(number, rounding_method: :round, targets: SUPER_ROUND_DEFAULT_TARGETS) return 0 unless number.positive? coef = 10**Math.log(number, 10).floor num = number / coef.to_f best_diff = best_target = nil targets.each do |target| diff = target - num next if rounding_method == :ceil && diff.negative? next if rounding_method == :floor && diff.positive? if best_diff.nil? || diff.abs < best_diff best_diff = diff.abs best_target = target end end (best_target.to_d * coef).to_f end |