Search code examples
ruby-on-railsruby-on-rails-3.1

number (currency) into english words


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.


Solution

  • 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"