Stop Writing Your Own Commify Functions

Writing your own commify function may well be right up there with writing your own web framework or templating system. Most of us have done it and it probably wasn’t worth the effort. Enter CLDR::Number. (I should note here that it’s not obvious from the name that this module will commify for you — that’s one of the reasons I’m writing this up.)

Let’s see if we can do this:

Easy, right? Not only does CLDR::Number handle commification (is that a word?) — it also does this correctly for various locales. If you’re trying to internationalize your application, this can save you a lot of time. Let’s look at the output:

You can see that the differences are significant enough that you don’t want to re-invent this wheel. The fact that we’re using a “Decimal” formatter here is a bit misleading. It’ll handle whole numbers just fine.

Let’s try it with some digits after the decimal place, though.

That works nicely as well.

Now, did I mention that this distribution includes a couple of other formatters? Let’s look at currency. That’s another tricky one.

The output is:

Crazy, right? I had no idea that representing a price in USD could vary so wildly across locales.

Let’s have a look at the last formatter, then.

The output looks like:

We can see here that the percent formatter rounds to the nearest percent by default. We can change that with an argument when creating the formatter.

Our output will then look like:

I could expand on the various arguments a bit more, but this is the gist of it. This is an extremely handy module which saves you from writing your own formatters and makes it easy for you to keep folks across the globe happy with your internationalization efforts.

I’ve personally already gotten a lot of use out of this code . May thanks to Nova Patch and Shutterstock for releasing it!

Addendum: Choosing the most specific locale

After I originally published this post, Tom Legrady was kind enough to reach out to me to say that relying on “en” as a locale may not always be what you want.  Consider the case of currency.  Let’s tweak our example to display various “en” locales.

Let’s have a look at the results:

If you look closely, you’ll see 4 distinct currency formats just across various “en” locales. I’ve sorted them by popularity across the various locales. (I should note that I was surprised at the outcome.)

So, if you can get to the most specific, correct locale for a user, it probably makes sense to use that locale. Thanks, Tom!