Class: NepaliNumber::Humanizer

Inherits:
Object
  • Object
show all
Defined in:
lib/nepali_number/humanizer.rb

Constant Summary collapse

UNITS =
[
  [10**17, "शंख"],
  [10**15, "पद्म"],
  [10**13, "नील"],
  [10**11, "खर्ब"],
  [10**9, "अर्ब"],
  [10**7, "करोड"],
  [10**5, "लाख"],
  [10**3, "हजार"],
  [10**2, "सय"]
].freeze

Class Method Summary collapse

Class Method Details

.human(number, precision: 2, strip_insignificant_zeros: true, units: UNITS) ⇒ Object

Raises:

  • (ArgumentError)


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/nepali_number/humanizer.rb', line 18

def human(number, precision: 2, strip_insignificant_zeros: true, units: UNITS)
  raise ArgumentError, "number is required" if number.nil?

  value = BigDecimal(number.to_s)
  sign = value.negative? ? "-" : ""
  absolute = value.abs

  unit_value, unit_name = units.find { |candidate_value, _| absolute >= candidate_value }
  return "#{sign}#{integer_string(absolute)}" unless unit_value

  scaled = absolute / unit_value
  scaled_text =
    if scaled.frac.zero?
      integer_string(scaled)
    else
      decimal_string(scaled, precision, strip_insignificant_zeros)
    end

  "#{sign}#{scaled_text} #{unit_name}"
end