# Convert units

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

Source: https://recipe-book.siraj.page/guides/convert-units/

Convert a quantity to a unit you choose with [`convert`](https://recipe-book.siraj.page/reference/core/units.md#convert), or let [`toSystem`](https://recipe-book.siraj.page/reference/core/units.md#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.

```ts
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](https://recipe-book.siraj.page/guides/convert-units.md#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](https://recipe-book.siraj.page/guides/author-recipes.md#read-regional-recipes) shows how to parse them. For UK pints, give those quantities in milliliters. [Units](https://recipe-book.siraj.page/reference/core/units.md#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](https://recipe-book.siraj.page/guides/convert-units.md#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 }`](https://recipe-book.siraj.page/reference/core/units.md#tosystemoptions), 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:

```ts
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](https://recipe-book.siraj.page/reference/core/units.md#tosystem) 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`](https://recipe-book.siraj.page/reference/core/resolving.md#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](https://recipe-book.siraj.page/guides/scale-a-recipe.md#resolve-a-recipe-for-display).

> **Note**
>
> Results such as 2.2046226218487757 lb aren't rounded. Round them for display with [`formatQuantity`](https://recipe-book.siraj.page/reference/core/formatting.md#formatquantity), which writes 2 ¼ lb.

## 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`](https://recipe-book.siraj.page/errors/incompatible_units.md) for cups to grams.

Instead, weigh the ingredient and give its weight as an [equivalent](https://recipe-book.siraj.page/guides/author-recipes.md#add-equivalents). `resolveRecipe` shows it to a reader who wants metric units:

```ts {9,16}
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`](https://recipe-book.siraj.page/reference/core/units.md#canconvert) before you call `convert`:

```ts
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](https://recipe-book.siraj.page/reference/core/units.md#range) convert to the same unit:

```ts {4-6}
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](https://recipe-book.siraj.page/reference/core/units.md#tosystem), 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`](https://recipe-book.siraj.page/reference/core/units.md#findunit), then check the conversion with [`canConvert`](https://recipe-book.siraj.page/reference/core/units.md#canconvert), which returns `false` instead of throwing:

```ts
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`](https://recipe-book.siraj.page/errors/invalid_argument.md) 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`](https://recipe-book.siraj.page/reference/core/units.md#converttemperature):

```ts
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`](https://recipe-book.siraj.page/reference/core/formatting.md#formattemperature) with `rounding: 'oven'`, as [Format oven temperatures](https://recipe-book.siraj.page/guides/display-quantities.md#format-oven-temperatures) shows.

## Reference

- [Units](https://recipe-book.siraj.page/reference/core/units.md) documents every unit and the conversion functions and types used here.
- [`incompatible_units`](https://recipe-book.siraj.page/errors/incompatible_units.md), [`unknown_unit`](https://recipe-book.siraj.page/errors/unknown_unit.md), and [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md) explain the errors these functions throw.
