Class: Istox::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/istox/helpers/formatter.rb

Class Method Summary collapse

Class Method Details

.money(input, currency:, round_mode: :half_up, precision: nil, position: :front, abs_num: false, hide_currency: false) ⇒ Object

format a money, eg. 20000.134 > SGD 20,000.14, position can be :front or :behind, abs_num: whether to absolute the number



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/istox/helpers/formatter.rb', line 22

def money(input, currency:, round_mode: :half_up, precision: nil, position: :front, abs_num: false, hide_currency: false)
  # precision = ::Istox::CommonHelper.get_currency_decimal(currency, precision)

  decimal_place = if precision.present?
                    precision
                  else
                    ::Istox::CommonHelper.get_currency_decimal(currency)
                  end

  result = number(input, round_mode: round_mode, precision: decimal_place, abs_num: abs_num)

  return result if hide_currency

  return currency + ' ' + result if position == :front

  result + ' ' + currency
end

.number(input, round_mode: :half_up, precision: 2, abs_num: false) ⇒ Object

format a number, eg. 20000.134 > 20,000.14



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/istox/helpers/formatter.rb', line 5

def number(input, round_mode: :half_up, precision: 2, abs_num: false)
  BigDecimal.mode(BigDecimal::ROUND_MODE, round_mode)

  input = 0 if input.blank?

  input = ::BigDecimal.new(input.to_s).round(precision, round_mode)

  input = input.abs if abs_num
  # result = format("%.#{precision}f", input) # may produce floating point error
  result = (input.truncate(precision).to_s('F') + '000000000000000000')[/.*\..{#{precision}}/]

  parts = result.to_s.split('.')
  parts[0].gsub!(/(\d)(?=(\d\d\d)+(?!\d))/, '\\1,')
  parts.join('.')
end