Module: NumberToCn

Included in:
Float, Integer
Defined in:
lib/number_to_cn/methods.rb,
lib/number_to_cn/version.rb

Constant Summary collapse

CN_T_TRANS =
[ "", "", "", "", "", "", "", "", "", "", "" ]
CN_T_TRANS_WITH_ZERO =
[ "", "", "", "", "", "", "", "", "", "", "" ]
CN_T_POSITION =
[ "", "", "", "" ]
CN_T_BIG =
[ "", "", "亿", "" ]
VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#float_wordsObject



46
47
48
49
50
51
# File 'lib/number_to_cn/methods.rb', line 46

def float_words
  before_point     = self.to_i
  after_point      = self.to_s.split(".")[1]
  after_point_zero = "" * (after_point.length - after_point.to_i.to_s.length)
  "#{before_point.int_words}#{after_point_zero}#{after_point.to_i.to_cn_clearly}"
end

#int_wordsObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/number_to_cn/methods.rb', line 16

def int_words
  return "" if self == 0

  num_arr = self.to_s.split('').reverse
  rst_arr = []

  writable = -1 
  #1: 都需要写;
  #0: 写一个零,后面的'千'不用写; 
  #-1:不需要写'千',也不需要写'零';

  num_arr.each_with_index do |value, index|
    writable = -1 if index%4 == 0
    cc = (index%4 == 0) ? CN_T_BIG[index/4] : ""
    aa = CN_T_TRANS[value.to_i]

    if value.to_i == 0
      bb = (writable == 1) ? "" : ""
      writable = (writable == 1) ? 0 : -1
    else
      bb = CN_T_POSITION[index%4]
      writable = 1
    end

    rst_arr << aa + bb + cc
  end

  rst_arr.reverse.join
end

#to_cn_clearlyObject



53
54
55
56
57
58
# File 'lib/number_to_cn/methods.rb', line 53

def to_cn_clearly
  to_s.split('')
      .delete_if{ |c| c =~ /\D/ }
      .map{ |c| CN_T_TRANS_WITH_ZERO[c.to_i] }
      .join
end

#to_cn_wordsObject



8
9
10
11
12
13
14
# File 'lib/number_to_cn/methods.rb', line 8

def to_cn_words
  if self.class == Fixnum
    int_words
  elsif self.class == Float
    float_words
  end
end