2012-05-29 113 views
0

我有一個生成發票的應用程序。該系統使用三種貨幣:磅,美元和歐元。作爲要求的一部分,發票必須以英文單詞顯示總金額。數字(貨幣)換成英文單詞

例如:
£100.50 - 一百磅和五十便士。
$ 100.50 - 一百美元和五十美分。
€100.50 - 一百歐元和五十美分。

我發現從2010年開始this,但它並沒有真正解決我的問題。 我想知道什麼是將數字轉換爲包括貨幣在內的單詞的最佳方式。
我想找到一個寶石來幫助我在這個問題上,但我可以找到...
任何建議是非常受歡迎的。

回答

2

您鏈接的帖子提到linguistics.gem - 因爲它可以爲您轉換數字,所有您需要做的是拆分主要和次要單位(即美元和美分/磅和便士),然後處理每個單位,然後重組與主要和次要單位名稱字符串,即

majorUnit.en.numwords dollars [and minorUnit.en.numwords cents] 
... 
puts 100.en.numwords + " dollars and " + 50.en.numwords + " cents" 
# => 100 dollars and fifty cents 

linguistics.gem一個好處是,它也可以處理單數/複數了你,當你只有你的主要/次要單位,如之一。 :

"penny".en.plural 
# => "pence" 
+0

嘿西蒙......非常感謝......我終於在你的回答中實現了我所需要的。 – gabrielhilal

0
def self.subhundred number 
    ones = %w{zero one two three four five six seven eight nine 
     ten eleven twelve thirteen fourteen fifteen 
     sixteen seventeen eighteen nineteen} 
    tens = %w{zero ten twenty thirty fourty fifty sixty seventy eighty ninety} 

    subhundred = number % 100 
    return [ones[subhundred]] if subhundred < 20 
    return [tens[subhundred/10], ones[subhundred % 10]] 
end 

def self.subthousand number 
     hundreds = (number % 1000)/100 
     tens = number % 100 
     s = [] 
     s = subhundred(hundreds) + ["hundred"] unless hundreds == 0 
     s = s + ["and"] if hundreds == 0 or tens == 0 
     s = s + [subhundred(tens)] unless tens == 0 
     s 
end 

def self.decimals number 
      return [] unless number.to_s['.'] 
      number = number.to_s.split('.')[1] 
      puts "num ---#{number}" 
      digits = subhundred number.to_i if number.to_i > 0 
      #digits.present? ? ["and"] + digits + ['cents'] : [] 
      digits.present? ? ["and"] + ['cents'] + digits : [] 
end 
def self.words_from_numbers number 
      steps = [""] + %w{thousand million billion trillion quadrillion quintillion sextillion} 
      result = [] 
      n = number.to_i 
      steps.each do |step| 
      x = n % 1000 
      unit = (step == "") ? [] : [step] 
      result = subthousand(x) + unit + result unless x == 0 
      n = n/1000 
      end 
      result = ["zero"] if result.empty? 
      result = result + decimals(number) 

      result.join(' ').gsub('zero','').strip 
end 

OutPut : 

    puts words_from_numbers(440100) => " US DOLLARS FOUR HUNDRED FOURTY THOUSAND AND ONE HUNDRED ONLY"