Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Fractions to Words

Tags:

php

fractions

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".

like image 343
Alexander Holsgrove Avatar asked Jan 18 '13 12:01

Alexander Holsgrove


People also ask

What is this fraction 1/3 in words?

When we write the fraction in words, we use a hyphen between the cardinal number and the ordinal number. Here are some examples: We pronounce 1/3 as one-third, 1/4 as one-fourth, and 1/8 as one-eighth.

Do you write out fractions in words?

Rule: Always spell out simple fractions and use hyphens with them. Example: One-half of the pies have been eaten. Rule: A mixed fraction can be expressed in figures unless it is the first word of a sentence. Example: We expect a 5 1/2 percent wage increase.

How do you write 2 3 in a sentence?

Fractions as Words For instance, we would write “2/3” as “two thirds”: He ate two thirds of the pizza by himself! This applies for most fractions.


1 Answers

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!
like image 189
Rawling Avatar answered Oct 13 '22 10:10

Rawling