Module: NumHelper

Extended by:
NumHelper
Included in:
NumHelper
Defined in:
lib/rails_com/utils/num_helper.rb

Constant Summary collapse

NUM =
['', '', '', '', '', '', '', '', '', ''].freeze
DEL =
['', '', '', ''].freeze
SUB_DEL =
['', ''].freeze
UNIT =
['', '', '亿', '', ''].freeze
DELIMITER_REGEX =
/(\d)(?=(\d\d\d\d)+(?!\d))/.freeze

Instance Method Summary collapse

Instance Method Details

#to_parts(num_str, unit: [], del: []) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rails_com/utils/num_helper.rb', line 24

def to_parts(num_str, unit: [], del: [])
  han_arr = num_str.split(',').reverse.map.with_index do |str, index|
    str = str.each_char.map { |i| NUM[i.to_i] }
    xx = ''
    str.zip(del[0..str.size - 1].reverse) do |st, de|
      if st != '' && de
        xx << st + de
      else
        xx << st unless xx.end_with?('')
      end
    end
    if xx.chomp!('')
      xx << (unit[index].to_s) << ''
    else
      xx << (unit[index].to_s)
    end
    xx
  end

  han_arr.reverse.join
end

#to_rmb(num) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/rails_com/utils/num_helper.rb', line 11

def to_rmb(num)
  left, right = num.to_s(:rounded, precision: 2, strip_insignificant_zeros: true, separator: '.', delimiter: ',', delimiter_pattern: DELIMITER_REGEX).split('.')

  left_str = to_parts(left, unit: UNIT, del: DEL)

  if right
    right_str = to_parts(right, del: SUB_DEL)
    left_str + right_str
  else
    left_str + ''
  end
end