Mixed numbers in Ruby / Rails

At Cook Smarts, we’re going to let people scale recipes.

When doubling a recipe, for instance, 1 1/4 cups would become 2 1/2 cups.

These are both mixed numbers, a combination of a whole number and a fraction. We show them to users instead of their fraction equivalents, 5/4 and 5/2.

Rails provides no built-in methods for doing calculations with mixed numbers, so we have to convert them to and from rationals before treating them as numbers.

A rational in Ruby is a number that can be expressed as a fraction. In most cases, all of the quantities in an app can be expressed as rationals.

That way, we can perform calculations and still show users pretty fractions (i.e. 2 1/2 instead of 5/2).

Convert a mixed number to a rational
for calculations

Unlike mixed numbers, rationals can be used in calculations. Use this function to convert a mixed number string into a rational.

Above, we split a mixed number into its integer and fraction components and add them together to form a rational (or whole number). The function can also handle decimals, integers, and regular fractions.

Note: This is not ready for negative mixed numbers.

Convert a rational to a mixed number
for the user

Use this method to convert a rational, like 3/2, into a mixed number that we can show to the user, like 1 1/2.

Above, we convert to a mixed number if the provided number is not an integer and it’s more than 1. Otherwise, we return the number as a string.

A note on precision

Rationals and integers are exact, while decimals and floats are sometimes not. 1/3 is precise, but 1.333333…. is not.

Never mix decimals and fractions if you want to maintain precision.

Hired.com brings Rails job offers to you. Free for candidates. Salaries from $75,000 to $250,000. Sign up now!

4 thoughts on “Mixed numbers in Ruby / Rails”

Leave a Reply