Recipe Book0.6.0

2.3Guides

Convert units

Convert quantities between units and measurement systems, show cups as grams, check units from user data, and convert oven temperatures.

§ 2.35 min readView as Markdown

Convert a quantity to a unit you choose with convert, or let toSystem choose the unit for a measurement system. In a React app, replace @recipe-book/core with @recipe-book/react/core in this page’s imports.

TypeScript
import { convert } from '@recipe-book/core'

convert({ amount: 1.25, unit: 'cup' }, 'ml') // { amount: 295.735295625, unit: 'ml' }
convert({ amount: 2, unit: 'lb' }, 'g') // { amount: 907.18474, unit: 'g' }

Quantities hold unit IDs, such as 'cup' and 'ml', rather than the text authors type, such as 'cups'; to read that text, see Check units from data. IDs are lowercase, so liters are 'l', not 'L'. Fluid ounces are 'fl-oz', because 'oz' measures mass. Cups, pints, quarts, gallons, and fluid ounces are US sizes, so 'cup' is about 237 mL, not a 250 mL metric cup, and a pint is about 473 mL, not a 568 mL UK imperial pint. For a recipe written with metric cups, write 'cup-metric', and for one written with Australian tablespoons, 'tbsp-au'; Read regional recipes shows how to parse them. For UK pints, give those quantities in milliliters. Units lists every ID and its size. convert converts mass to mass and volume to volume. To show cups as grams, see Convert cups to grams.

Convert to metric or US units

When a reader switches between metric and US units, use toSystem. Its systems are 'metric' and 'us', and there’s no imperial system. It returns a quantity unchanged when it’s already in the system (tsp, tbsp, and count units such as clove belong to both systems) or has no unit, and converts the rest to the unit a cook would measure with. US volume also lands on a cup or spoon measure unless you pass { exact: true }, which keeps the unit but not the rounding. Without it, an amount or range end too small to land on ⅛ tsp stays exact, and a range whose ends convert to different amounts but would land on the same measure keeps those amounts:

TypeScript
import { toSystem } from '@recipe-book/core'

toSystem({ amount: 8, unit: 'oz' }, 'metric') // { amount: 226.796185, unit: 'g' }
toSystem({ amount: 1, unit: 'kg' }, 'us') // { amount: 2.2046226218487757, unit: 'lb' }
toSystem({ amount: 150, unit: 'ml' }, 'us') // { amount: 10, unit: 'tbsp' }
toSystem({ amount: 3, unit: 'tbsp' }, 'metric') // { amount: 3, unit: 'tbsp' }

The toSystem reference lists the units each system uses, when it picks each one, and how far a measure can be from the exact amount.

To show a whole recipe in one system, use resolveRecipe instead. It uses the first of each ingredient’s quantity and equivalents that belongs to that system. When none does, it converts the first weight among them for a metric reader, else the quantity, the way toSystem does. For a US reader it converts the quantity, so a volume stays a volume. See Resolve a recipe for display.

Convert cups to grams

A cup has no fixed weight. It depends on the ingredient and on how the cup is filled: a cup of flour weighs less than a cup of sugar, and flour scooped from the bag weighs more than flour spooned in and leveled. So Recipe Book has no table of densities, and convert throws incompatible_units for cups to grams.

Instead, weigh the ingredient and give its weight as an equivalent. resolveRecipe shows it to a reader who wants metric units:

TypeScript
import { parseRecipe, resolveRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Pancakes',
  ingredients: [
    {
      name: 'all-purpose flour',
      quantity: '1 ½ cups',
      equivalents: ['190 g'],
    },
    { name: 'buttermilk', quantity: '1 ¼ cups' },
  ],
})
if (!result.success) throw result.error

const metric = resolveRecipe(result.data, { system: 'metric' })
const [flour, buttermilk] = metric.ingredients[0]?.items ?? []
flour?.quantity // { amount: 190, unit: 'g' }
flour?.origin // 'equivalent'
buttermilk?.quantity // { amount: 295.735295625, unit: 'ml' }
buttermilk?.origin // 'converted'

A reader who wants US units still sees cups of both. An equivalent in ounces works too: for a metric reader, 6.7 oz gives about 189.94 g, with the origin 'converted'. Give the weight in grams to show a metric reader the number you weighed.

A recipe written in grams works the other way round: measure the ingredient in cups, and give that as the equivalent. Flour with quantity: '190 g' and equivalents: ['1 ½ cups'] resolves to { amount: 1.5, unit: 'cup' } for a reader who wants US units. Without the equivalent, its grams become ounces, about 6.7 oz.

To convert a quantity yourself, check it with canConvert before you call convert:

TypeScript
import { canConvert, convert, type Quantity } from '@recipe-book/core'

function inGrams(quantity: Quantity) {
  if (!canConvert(quantity.unit, 'g')) return undefined
  return convert(quantity, 'g')
}

inGrams({ amount: 8, unit: 'oz' }) // { amount: 226.796185, unit: 'g' }
inGrams({ amount: 1.5, unit: 'cup' }) // undefined

Convert ranges

Both ends of a range convert to the same unit:

TypeScript
import { convert, toSystem } from '@recipe-book/core'

convert({ amount: { min: 2, max: 3 }, unit: 'tbsp' }, 'tsp') // { amount: { min: 6, max: 9 }, unit: 'tsp' }
toSystem({ amount: { min: 3, max: 5 }, unit: 'cup' }, 'metric') // { amount: { min: 709.7647095, max: 1182.9411825 }, unit: 'ml' }
toSystem({ amount: { min: 120, max: 210 }, unit: 'ml' }, 'us') // { amount: { min: 8, max: 14 }, unit: 'tbsp' }
toSystem({ amount: 120, unit: 'ml' }, 'us') // { amount: 0.5, unit: 'cup' }

In metric and for US weights, toSystem lets the low end choose the unit, so 3–5 cups stays in milliliters even though 5 cups alone is 1.1829411825 L. US volume needs both ends to land on the same set of measures, so 120–210 mL is 8–14 tbsp even though 120 mL alone is ½ cup: 210 mL lands on no cup measure.

Check units from data

Units from users or a CMS arrive as text, such as an abbreviation like 'Tbsp' or a name like 'cloves'. Turn the text into a unit ID with findUnit, then check the conversion with canConvert, which returns false instead of throwing:

TypeScript
import { canConvert, convert, findUnit } from '@recipe-book/core'

function toMilliliters(amount: number, text: string) {
  const unit = findUnit(text)
  if (!canConvert(unit, 'ml')) return undefined
  return convert({ amount, unit }, 'ml')
}

toMilliliters(3, 'Tbsp') // { amount: 44.36029434375, unit: 'ml' }
toMilliliters(2, 'cloves') // undefined
toMilliliters(1, 'knob') // undefined

canConvert checks units only, so check amounts from data too: convert throws invalid_argument for an amount that isn’t a finite number greater than 0 or a range of them, for a range whose min is greater than its max, and for an amount above about 1e300 or below about 1e-300 whose conversion overflows to Infinity or underflows to 0.

Convert temperatures

Convert oven temperatures with convertTemperature:

TypeScript
import { convertTemperature } from '@recipe-book/core'

convertTemperature({ value: 180, unit: 'C' }, 'F') // { value: 356, unit: 'F' }
convertTemperature({ value: 350, unit: 'F' }, 'C') // { value: 176.66666666666666, unit: 'C' }

To show them as 350 °F and 180 °C, pass them to formatTemperature with rounding: 'oven', as Format oven temperatures shows.

Reference

Contents