Getting Alexa To Pronounce Ordinals

Today, I’m working on a project that requires Alexa to say things like “first,” “second,” or “twenty-first.”  I’ve gone through a few iterations of creating these ordinal strings.

First: Brute Force Attempt

I started the easy way: I created a hard-coded switch statement for the values from 1 – 10, and used a helper function to feed me the appropriate return value as a string..  Not the most elegant, but it got the job done.

Second: Slightly More Elegant and Scaleable

As my application grew, I realized that I would now need the values from 1 – 50 available in my application.  I added to my switch statement…until I got to 15.  At that point, I realized I needed a new solution that could scale to any number I passed in.  So I started writing some logic to append “st” to numbers that ended in 1, “nd” to numbers that ended in 2, “rd” to numbers that ended in 3, and “th” to pretty much everything else.  I had to write some exception cases for 11, 12, and 13.

It was at this point that I made an amazing discovery.

Third: Alexa is already too smart for me.

While playing with my second solution, I used the Voice Simulator that is available when you are building an Alexa skill.  I wanted to see if Alexa would pronounce the words the same if I just appended the suffixes like “th” or “nd” to the actual number value, rather than trying to convert the whole thing to a word.

This is where the discovery was made.

I tried getting her to say “4th,” and she pronounced it as I expected: “fourth.”

On a whim, I added “th” to the number 2, which would normally be incorrect.  She pronounced it “second.”  I had the same experience with “1th,” which she still got correct as “first.”

If you append “th” to the end of any number, Alexa will pronounce the appropriate ordinal.

My mind was slightly blown today.  Thanks, Alexa.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s