Human readable fractional numbers in Rails?

364 views Asked by At

I love the pluralize method in Rails. I'm hoping there's a similar mechanism for fractional numbers where they can be more human readable. For example, this would be ideal:

> include ActionView::Helpers::TextHelper
> pluralize(2.0, 'donut')
 => "2.0 donuts" 
> pluralize_and_humanize(2.0, 'donut')
 => "2 donuts"
> pluralize_and_humanize(2.5, 'donut')
 => "2 and a half donuts"
> pluralize_and_humanize(1.0, 'donut')
 => "1 donut"
> pluralize_and_humanize(0.5, 'donut')
 => "half a donut"
> pluralize_and_humanize(0.75, 'donut')
 => "3/4 of a donut"

Anything built in to rails? Any gems I can use?

1

There are 1 answers

0
Carlos Drew On

Actually, I think I have something for you.

Set up the rails fractions plugin in your project. Then, write your own helper, like so: (pseudocode)

def pluralize_and_humanize(number, string)
  split number into integer and fractional part -> whole, fraction

  convert fraction to [nice_fraction][2] if there is a fractional component

  output whole number + nice_fraction + pluralized string
end

Now, I'm not helping you with outputting "and a half" or "and a quarter" but I think '2 1/2' would at least be better than 2.5.