中文数字转换阿拉伯数字
程序员文章站
2023-12-22 22:10:46
...
require 'rubygems'
require 'jcode'
$KCODE='u'
def main(str)
num=0
if str.to_s.match("亿")
str.to_s.match(/(.+)亿(.+)/)
num1=conv($1.to_s)*100000000
num2=conv($2.to_s)
num=num1+num2
else
num=conv(str.to_s)
end
return num
end
def conv(str)
num=0
temp_num=0
i=0
str_length=str.each_char.count
str.each_char do |n|
ch,ch_type=num_type(n)
if ch_type==1
temp_num=ch
num+=ch if i==str_length-1
elsif ch_type==0
num+=temp_num*ch if ch < num
num=(num+temp_num)*ch if ch >num
temp_num=0
end
i+=1
end
return num
end
def num_type(str)
case str
when "万"
return 10000,0
when "千"
return 1000,0
when "百"
return 100,0
when "十"
return 10,0
else
return num(str),1
end
end
def num(str)
return result=case str
when "一"
1
when "二"
2
when "三"
3
when "四"
4
when "五"
5
when "六"
6
when "七"
7
when "八"
8
when "九"
9
when "零"
0
end
end
puts main("三千零九十万六千四百零三亿九千零三万零五百零一")