Converting numbers to English words

adoptionneocpanismwhipupathon Thu 5 June 2014

Three years ago I adopted Sean Burke's Lingua::EN::Numbers, as a result of reviewing CPAN modules for spelling numbers in English. Last month (May) I adopted two more of Sean's Lingua::EN:: modules, Lingua::EN::Numbers::Ordinate and Lingua::EN::Numbers::Years. Today Sean casually challenged me to add to the collection, which resulted in the first release of Lingua::EN::Fractions.

Lingua::EN::Numbers provides a function num2en, which takes a number and returns it spelled out in English words:

my $number = 263;
my $as_words = num2en($number);    # "two hundred and sixty-three"

Lingua::EN::Numbers::Years provides a function year2en, which takes a number which is interpreted as a year, and returned spelled out:

my $year     = 1984;
my $as_words = year2en($number);   # "nineteen eighty-four"

Lingua::EN::Numbers::Ordinate will convert a cardinal number to an ordinal:

my $number  = 14;
my $ordinal = ordinate($number);   # "fourteenth"

And then in email today, Sean told me ideas for additional modules, which he suggested I could "cobble together in a few minutes from the existing stuff". That was a good challenge, so tonight I cobbled together a first release of Lingua::EN::Fractions:

use Lingua::EN::Fractions qw/ fraction2words /;

my $fraction = '3/4';
my $as_words = fraction2words($fraction);   # "three quarters"

Sean was right: this is just a small amount of code that uses num2en_ordinal from Lingua::EN::Numbers. At the moment it's very basic, but I'll expand coverage, and add support for Number::Fraction.

I'm working through some Perl books at the moment, so this module is a good opportunity to try doing some things a bit differently. I wrote my first regexp using /x today!

I had my fastest-ever pull request following this post — Nick Patch fixed a typo in the doc. He also pointed out that I'm converting "-2/5" as "minus two fifths", but Americans will expect to get "negative two fifths". Need to decide what the best interface is for selecting US or UK English, or 'minus' vs 'negative'?

comments powered by Disqus