Class: ReeNumber::NumberToRounded

Inherits:
Object
  • Object
show all
Includes:
Ree::FnDSL
Defined in:
lib/ree_lib/packages/ree_number/package/ree_number/functions/number_to_rounded.rb

Constant Summary collapse

DEFAULTS =
{
  precision: 3,
  significant: false,
  strip_insignificant_zeros: false,
  delimiter: "",
  round_mode: :default
}.freeze

Instance Method Summary collapse

Instance Method Details

#call(number, **opts) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/ree_lib/packages/ree_number/package/ree_number/functions/number_to_rounded.rb', line 51

def call(number, **opts)
  options = DEFAULTS.merge(opts)

  rounded_number = round_helper(
    number, 
    **slice(
      options, 
      [:precision, :significant, :round_mode]
    )
  )

  if precision = options[:precision]

    if options[:significant] && precision > 0
      digits = digit_count(rounded_number)
      precision -= digits
      precision = 0 if precision < 0
    end

    formatted_string = 

      if rounded_number.finite?
        s = rounded_number.to_s("F")
        a, b = s.to_s.split(".", 2)

        if precision != 0
          b << "0" * precision
          a << "."
          a << b[0, precision]
        end
        a
      else 
        "%f" % rounded_number
      end

  else 
    formatted_string = rounded_number
  end

  delimited_number = number_to_delimited(formatted_string, **slice(options, [:separator, :delimiter]))
  options[:strip_insignificant_zeros] ? format_number(delimited_number) : delimited_number
end