如何将数字转换成英语

Project Euler Problem 17 的启发,写了(其实是改写)一个能把数字转换成英语的Ruby 过程。

# zero, one, two, three, four, five, six, seven, eight, nine, ten,
# elevent, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, ...
# thirty, forty, fifty, sixty, seventy, eighty, ninety
# X hundred and X-X
# one thousand

$less_than_twenty = %w{zero one two three four five six seven eight nine ten elevent twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen}
$tens = %w{"" "" twenty thirty forty fifty sixty seventy eighty ninety}
def triple(n, unit)
  str = ""
  hundreds = n / 100
  low_digit = n % 100
  units_digit = n % 10
  str += $less_than_twenty[hundreds] + " hundred and " if hundreds != 0
  case low_digit
    when 0
      str.chomp!(" and ")
    when 1 .. 19
      str += $less_than_twenty[low_digit]
    when 20, 30, 40, 50, 60, 70, 80, 90
      str += $tens[low_digit/10]
    else
      str += $tens[low_digit/10] + "-" + $less_than_twenty[units_digit]
  end
  str += unit
end

def num2str(n)
  str = ""
  if n / 1_000_000 > 0
    str += triple(n / 1_000_000, " million ")
  end
  if (n % 1_000_000) / 1_000 > 0
    str += triple((n % 1_000_000) / 1_000, " thousand ")
  end
  if n % 1_000 > 0
    str += triple(n % 1_000, "")
  end
  str
end

p num2str(123_456_789)

由于英语里面是千进制,故可以看成一个处理1, 000 以内的过程附加上单位(billion,million,thousand)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值