Reputation: 10769
I have an application that generate invoices. The system works with three currencies: Pounds, US Dollars and Euros. As part of the requirements, invoices must have the total amount displayed in english words.
For example:
£100.50 - One hundred Pounds and fifty pences.
$100.50 - One hundred US Dollars and fifty cents.
€100.50 - One hundred Euros and fifty cents.
I found this post from 2010, but It doesn't really solve my problem.
I would like to know what is the best way to convert numbers into words including the currency.
I am trying to find a gem to help me on this matter, but I could find...
Any suggestion is very welcome.
Upvotes: 0
Views: 5085
Reputation: 669
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"
Upvotes: 0
Reputation: 8694
The post you linked mentions linguistics.gem - since it can convert the numbers for you, all you need to do is split out the major and minor units (i.e. dollars and cents/pounds and pence), process each, then recombine into a string with the major and minor unit names, i.e.
majorUnit.en.numwords dollars [and minorUnit.en.numwords cents]
...
puts 100.en.numwords + " dollars and " + 50.en.numwords + " cents"
# => 100 dollars and fifty cents
A bonus of linguistics.gem is that it can also handle singular/plural for you for when you have only one of your major/minor units, eg.:
"penny".en.plural
# => "pence"
Upvotes: 2