File: round.rb

package info (click to toggle)
ruby-backports 3.25.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,912 kB
  • sloc: ruby: 11,759; makefile: 6
file content (25 lines) | stat: -rw-r--r-- 707 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
if Integer.instance_method(:round).arity.zero?
  require 'backports/tools/alias_method_chain'
  require 'backports/tools/arguments'

  class Integer
    def round_with_digits(ndigits=0)
      ndigits = Backports::coerce_to_int(ndigits)
      case
      when ndigits.zero?
        self
      when ndigits > 0
        raise RangeError if ndigits >= 1<<31
        Float(self)
      else
        pow = 10 ** (-ndigits)
        return 0 if pow.is_a?(Float) # when ndigits hugely negative
        remain = self % pow
        comp = self < 0 ? :<= : :<
        remain -= pow unless remain.send(comp, pow / 2)
        self - remain
      end
    end
    Backports.alias_method_chain self, :round, :digits
  end
end