Abbreviating Numbers in Rails

I needed to abbreviate numbers in Rails so that they were shorter and easier to read.  Rails has a great built in method, number_to_human.  However, I didn’t like how number_to_human displays without any customization.

My main issue was that instead of spelling out the entire number, I just wanted to put a letter abbreviation.  In addition, I didn’t want a space between the number and its text description.

For example, “out of the box”, if you do:

number_to_human(1234)

You will get:

“1.23 Thousand”

Instead, I wanted 1.23K.

Luckily, I found this StackOverflow answer by jdoe.

To format it like this, you just need to add these values to config/locales/en.yml (or whatever you’re using as your 18n locale):

(under "en:")
  number:
    human:
      decimal_units:
        format: "%n%u"
        units:
          unit: ""
          thousand: K
          million: M
          billion: B
          trillion: T
          quadrillion: Q

Advertisements