Number to word in Thai
Posted by Revolution
อยู่ในภาคทดสอบ แบ่งเป็น 2 แบบคืออ่านธรรมดากับแบบค่าเงิน
ทดสอบได้ที่ num2word
class Number def initialize @unit = %w[ศูนย์ หนึ่ง สอง สาม สี่ ห้า หก เจ็ด แปด เก้า] @qtys = ["แสน", "หมื่น", "พัน", "ร้อย", "สิบ", "หน่วย"] @mils = "ล้าน" @zero = "ศูนย์" @twenty = "ยี่" @unitone = "เอ็ด" end def self.th_word(number) Number.new.to_s(number) end def self.th_currency(number) Number.new.to_s_currency(number) end def self.commify(number) (s=number.to_s;x=s.length;s).rjust(x+(3-(x%3))).gsub(/(\d)(?=\d{3}+(\.\d*)?$)/, '\1,') end def to_s(value) if (number = value.to_s.split(".");number.length) >2 then return ("'.' more than 1") end re = [] f = to_s_float(number[1]) if !number[1].nil? out = to_s_decimal(number[0]) re[0] = f if !f.nil? re[1] = out if !f.nil? then re[2] = re[1] + "จุด" + re[0] else re[2] = re[1] end return re.reverse end def to_s_currency(value) w = to_s(value).reverse f = value.to_s.gsub(/(\w*)+\./,"0.").to_f if !w[0].nil? w[0] = to_s_decimal((f * 100.0).round.to_s) if !f.nil? if !f.nil? then w[2] = w[1] + "จุด" + w[0] else w[2] = w[1] end return w.reverse end def to_s_float(value) return float_wordify(value).flatten.compact.join(' ').gsub(/ ,/,',') end def to_s_decimal(value) return quantify(value).flatten.compact.join(' ').gsub(/ ,/,',') end private def padded_groups(v) #make number to be 3 units per slot by fill zero infront (x%3 =0) out = [] padded = (s=v.to_s.gsub(/\D/i,"");x=s.length;s).rjust(x+(6-(x%6))).gsub(/ /,'0') padded.scan(/.{6}/) end def wordify(v) out = [] @unitone = "หนึ่ง" if v.to_i == 1 for cur in 0 .. v.length - 1 if cur ==4 and v[cur] == '2'[0] out << @twenty elsif cur ==4 and v[cur] == '1'[0] out << "" elsif cur ==5 and v[cur] == '1'[0] out << @unitone else out << @unit[v[cur]-'0'[0]] end end return out end def float_wordify(v) out = [] for cur in 0 .. v.length - 1 out << @unit[v[cur]-'0'[0]] end out.pop while out.last == @zero return out end def quantify(v) v = padded_groups(v).reverse pos = v.length - 1 out = [] while pos >= 0 if v[pos] == ',' out << ',' next end word = wordify(v[pos]) for po in 0 .. word.length - 1 if word[po] == @zero then next end if @qtys[po] != "หน่วย" then out << word[po] + @qtys[po] else out << word[po] end end out <<@mils if pos > 0 pos -= 1 end out.shift while out.first == @mils out << @zero if out.length.zero? return out end end




