Search code examples
phpfractions

Convert Fractions to Words


I'd like to know if there is a neat way to convert 1/2, 1/4, 5/8 into words (half, quarter, five eighths) using PHP.

I've got a product data feed, and need to create a clean URL for each product based on the name. Some have measurements like 1/4" and currently I swap out any non letter/numbers leaving me with "14" in this case. It would be more useful to convert this fraction into "quarter".


Solution

  • No, there is no neat way to do this.

    You'll need to

    • Implement an int-to-cardinal-string converter for the numerators
    • Modify this into an int-to-ordinal-string converter for the denominators ("third" instead of "three" etc. without also making "twenty-three" into "twentieth third")
    • Add some special cases ("second" -> "half", "fourth" -> "quarter" if you're not American... "first" -> ""?)
    • Optionally implement a simplifier so "2/4" => "half" not "two quarters"
    • Don't forget to pluralize your denominator if necessary!