# Display quantities

> Format quantities, ingredient lines, oven temperatures, and cooking times as text, and mark up a quantity's parts.

Source: https://recipe-book.siraj.page/guides/display-quantities/

Turn a quantity into text a cook can measure with [`formatQuantity`](https://recipe-book.siraj.page/reference/core/formatting.md#formatquantity). It rounds cups, spoons, and the other units in the first row of its rounding table to the nearest ⅛ or ⅓ and writes them as fractions, or, below ⅛, as a decimal such as `0.1 tsp`. It rounds grams, liters, and their multiples to sensible decimals, and picks a singular or plural label. In a React app, replace `@recipe-book/core` with `@recipe-book/react/core` in this page's imports. Pass `formatQuantity` a quantity, such as one from [`toSystem`](https://recipe-book.siraj.page/reference/core/units.md#tosystem):

```ts {5}
import { formatQuantity, toSystem } from '@recipe-book/core'

formatQuantity({ amount: 1.5, unit: 'cup' }) // '1 ½ cups'
formatQuantity({ amount: { min: 2, max: 3 }, unit: 'tbsp' }) // '2–3 tbsp'
formatQuantity(toSystem({ amount: 250, unit: 'ml' }, 'us')) // '1 cup'
```

250 mL is 1.06 cups, and `toSystem` lands it on the nearest [cup measure](https://recipe-book.siraj.page/reference/core/units.md#tosystem), 1 cup. Every formatting function joins each unit to the number before it with a no-break space (U+00A0), also called a non-breaking space or `&nbsp;`, so a line never breaks between them. The results in these docs contain that character, so a test that compares against a regular space doesn't match.

The formatting functions write fractions as single characters, so some fractions look different when your font lacks them. Many web fonts' Latin subsets, such as Fontsource's, have ¼, ½, and ¾ but not ⅓, ⅔, ⅛, ⅜, ⅝, or ⅞ (U+2150–215F). The browser draws those in a fallback font, so ⅓ looks different from ½. To fix a fraction in the wrong font, add an `@font-face` rule with `unicode-range: U+2150-215F` and a file of the same font that has them, such as one that isn't subsetted, or pass [`fractions: false`](https://recipe-book.siraj.page/guides/display-quantities.md#change-labels-fractions-and-locales) to write decimals.

## Show metric or US units

To show a quantity in the reader's measurement system, pass it through `toSystem` first:

```ts
import { formatQuantity, toSystem } from '@recipe-book/core'

formatQuantity(toSystem({ amount: 1.5, unit: 'cup' }, 'metric')) // '355 mL'
formatQuantity(toSystem({ amount: 8, unit: 'oz' }, 'metric')) // '227 g'
formatQuantity(toSystem({ amount: 2, unit: 'tbsp' }, 'metric')) // '2 tbsp'
```

Spoons read the same in both systems, because tsp and tbsp belong to both. The 20 mL Australian tablespoon, `tbsp-au`, belongs only to metric, so for a recipe read with [`units: { tbsp: 'tbsp-au' }`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantityoptions), `toSystem` turns its 1 tbsp into 4 tsp under `'us'`. The text uses each unit's label rather than its ID, so `ml` reads as mL and `l` as L. To show a whole recipe in the reader's system, use [`resolveRecipe`](https://recipe-book.siraj.page/reference/core/resolving.md#resolverecipe) instead, as [Resolve a recipe for display](https://recipe-book.siraj.page/guides/scale-a-recipe.md#resolve-a-recipe-for-display) shows.

## Format ingredient lines

[`formatIngredient`](https://recipe-book.siraj.page/reference/core/formatting.md#formatingredient) formats a whole line from a parsed recipe: the quantity, any size in parentheses, the name, and the note. These examples use the sample recipe from `examples/node-script`:

recipe.ts
```ts title="recipe.ts"
import type { RecipeInput } from '@recipe-book/core'

export const pancakes = {
  name: 'Buttermilk pancakes',
  servings: 4,
  times: { prep: 10, cook: 15 },
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cups', equivalents: ['190 g'] },
    { name: 'sugar', quantity: '2 tbsp', equivalents: ['25 g'] },
    { name: 'baking powder', quantity: '2 tsp' },
    { name: 'buttermilk', quantity: '1 ¼ cups' },
    { name: 'egg', plural: 'eggs', quantity: 2 },
    {
      name: 'butter',
      quantity: '3 tbsp',
      note: 'melted',
      equivalents: ['42 g'],
    },
    { name: 'maple syrup', note: 'to serve' },
  ],
  steps: [
    'Whisk the dry ingredients in a large bowl.',
    'Whisk the buttermilk, eggs, and butter, then fold into the dry ingredients.',
    'Cook ¼-cup portions on a buttered griddle, 2–3 minutes per side.',
  ],
} satisfies RecipeInput
```

Pass each ingredient as `{ ingredient }`:

```ts {9}
import { formatIngredient, parseRecipe } from '@recipe-book/core'
import { pancakes } from './recipe.ts'

const result = parseRecipe(pancakes)
if (!result.success) throw result.error

for (const section of result.data.ingredients) {
  for (const ingredient of section.items) {
    console.log(formatIngredient({ ingredient }).text)
  }
}
```

Output
```txt title="Output"
1 ½ cups all-purpose flour
2 tbsp sugar
2 tsp baking powder
1 ¼ cups buttermilk
2 eggs
3 tbsp butter, melted
maple syrup, to serve
```

Besides `text`, the result has the `quantity`, any [`size`](https://recipe-book.siraj.page/guides/display-quantities.md#show-the-size-of-a-can), the `name`, and the `note` on their own, so you can style each one. The text adds nothing for `optional: true`, so check `ingredient.optional` and mark it in your markup. A name or note keeps any "optional" it has, as in `'1 cup flour, optional for dusting'`.

To show the recipe in the reader's measurement system or for a number of servings, pass `formatIngredient` each item of a [resolved recipe](https://recipe-book.siraj.page/reference/core/resolving.md#resolvedingredient) as it is, with the resolved recipe's `system`, as [Display scaled ingredients](https://recipe-book.siraj.page/guides/scale-a-recipe.md#display-scaled-ingredients) does. The item holds the converted or scaled `quantity`, and `system` puts a can's size in the same system. Passing `{ ingredient: item.ingredient }` instead shows the quantity as written, so a metric reader would see 1 ½ cups of flour rather than 190 g.

### Show the size of a can

A can, a package, a stick, and the other [count units](https://recipe-book.siraj.page/reference/core/units.md#units) say how many, not how much, so a line in one usually gives the size too, as a mass or volume equivalent. `formatIngredient` shows that size in parentheses after the quantity, in the system you pass it. To a US reader, `1 (28 oz) can crushed tomatoes` reads 1 can (28 oz) crushed tomatoes. To a metric reader, it reads 1 can (794 g) crushed tomatoes.

```ts
import {
  formatIngredient,
  parseIngredientLine,
  resolveIngredient,
  type System,
} from '@recipe-book/core'

const show = (text: string, system: System) => {
  const line = parseIngredientLine(text)
  if (!line.success) throw line.error
  return formatIngredient(resolveIngredient(line.data, { system }), { system })
    .text
}

show('2 (15 oz) cans chickpeas', 'metric') // '2 cans (425 g each) chickpeas'
show('Three 8-ounce (680g) packages cream cheese', 'us') // '3 packages (8 oz each) cream cheese'
show('Three 8-ounce (680g) packages cream cheese', 'metric') // '3 packages (227 g each) cream cheese'
show('6 slices (5 oz) bacon', 'us') // '6 slices (5 oz total) bacon'
```

For any count but exactly 1, the size shows for one item, then "each". When that figure times the count, both as displayed, is more than 2% off the total, the total shows instead, then "total": the bacon's 5 oz over 6 slices would display as ⅞ oz a slice, which comes to 5 ¼ oz. [`formatIngredient`](https://recipe-book.siraj.page/reference/core/formatting.md#formatingredient) has the details, including count ranges and which equivalent becomes the size.

## Format oven temperatures

[`formatTemperature`](https://recipe-book.siraj.page/reference/core/formatting.md#formattemperature) writes whole degrees by default. A converted oven temperature rarely lands on a dial setting, so pass `rounding: 'oven'` to round to the nearest 10 °C or 25 °F, the way recipes write them:

```ts {6}
import { convertTemperature, formatTemperature } from '@recipe-book/core'

const oven = convertTemperature({ value: 350, unit: 'F' }, 'C')

formatTemperature(oven) // '177 °C'
formatTemperature(oven, { rounding: 'oven' }) // '180 °C'
```

A recipe's temperatures are in its step text, so to show a step in the reader's system, find them with [`segmentStepText`](https://recipe-book.siraj.page/reference/core/units.md#segmentsteptext), as its `showStep` example does. `showStep` uses `rounding: 'oven'` only for an oven setting, because oven rounding would show chicken's 165 °F as 70 °C, not 74 °C. In React, [`<Recipe.StepText>`](https://recipe-book.siraj.page/reference/react/steps.md#steptext) shows a step this way, in [`<Recipe.Root>`](https://recipe-book.siraj.page/reference/react/root.md)'s measurement system. To convert a step's mass and volume quantities as well, find them with [`segmentStepQuantities`](https://recipe-book.siraj.page/reference/core/units.md#segmentstepquantities); in React, [`<Recipe.ConvertedStepText>`](https://recipe-book.siraj.page/reference/react/steps.md#convertedsteptext) converts both.

## Format cooking times

A recipe's times, such as its cooking time, are minutes. [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) turns ISO 8601 durations such as `PT1H15M` into minutes too. Format them with [`formatDuration`](https://recipe-book.siraj.page/reference/core/formatting.md#formatduration):

```ts
import { formatDuration } from '@recipe-book/core'

formatDuration(15) // '15 min'
formatDuration(75) // '1 hr 15 min'
formatDuration(75, { unitDisplay: 'long' }) // '1 hour 15 minutes'
```

In React, [`<Recipe.Times>`](https://recipe-book.siraj.page/reference/react/times.md) formats each of a recipe's times this way, with Root's `locale`, and lists them with their labels.

## Change labels, fractions, and locales

Every formatting function takes `unitDisplay` and `locale`, though `unitDisplay` has no effect on [`formatServings`](https://recipe-book.siraj.page/reference/core/formatting.md#formatservings) and [`formatYield`](https://recipe-book.siraj.page/reference/core/formatting.md#formatyield). The quantity functions also take `fractions` and `rounding`:

```ts
import { formatQuantity } from '@recipe-book/core'

formatQuantity({ amount: 0.5, unit: 'tsp' }, { unitDisplay: 'long' }) // '½ teaspoon'
formatQuantity({ amount: 1.5, unit: 'cup' }, { fractions: false }) // '1.5 cups'
formatQuantity({ amount: 2.5, unit: 'g' }, { locale: 'de-DE' }) // '2,5 g'
```

Only numbers follow `locale`. Labels stay English unless you pass a label pack as `labels`, which [Localize recipes](https://recipe-book.siraj.page/guides/localize-recipes.md) covers. No shipped pack labels the US units, such as `cup` and `oz`, so they keep their English labels. A React app imports its pack from [`@recipe-book/react/labels`](https://recipe-book.siraj.page/reference/react/labels.md) and passes it as `labels` to [`<Recipe.Provider>`](https://recipe-book.siraj.page/reference/react/provider.md) or [`<Recipe.Root>`](https://recipe-book.siraj.page/reference/react/root.md). Most tags take their numbers from the runtime's `Intl` data, so see the caution under [`FormatOptions`](https://recipe-book.siraj.page/reference/core/formatting.md#formatoptions) before you render on both a server and a browser.

For a language with no pack (i18n), translate units yourself: [`formatQuantityToParts`](https://recipe-book.siraj.page/reference/core/formatting.md#formatquantitytoparts) returns the unit as its own part, so replace its text with your translation of the quantity's `unit`. In React, [`<Recipe.IngredientQuantity>`](https://recipe-book.siraj.page/reference/react/ingredients.md#ingredientquantity) shows English labels without a pack, so render your own quantity in its place: call the function that [`useFormatIngredient`](https://recipe-book.siraj.page/reference/react/hooks.md#useformatingredient) returns with each item, and replace the unit part of its `quantityParts` the same way. [Labels](https://recipe-book.siraj.page/guides/make-a-recipe-accessible.md#translate-the-built-in-text) translate the rest of the built-in text, but a range's `rangeSeparator` part is only the dash, so a quantity rendered from `quantityParts` loses the hidden `to` that, in Chrome and Firefox, takes the dash's place. To keep it, render the dash in a `<span aria-hidden="true">`, and put your translation of "to", with a space on each side, beside it in visually hidden text, as `<Recipe.IngredientQuantity>` does. Give that text `white-space: pre` rather than the `nowrap` that many visually hidden classes set, or WebKitGTK can name the list item itself "1to2 lemons, zested".

## Mark up the parts

To style the amount and the unit separately, use [`formatQuantityToParts`](https://recipe-book.siraj.page/reference/core/formatting.md#formatquantitytoparts). It splits the text `formatQuantity` returns into typed parts:

```ts
import { formatQuantityToParts } from '@recipe-book/core'

formatQuantityToParts({ amount: { min: 2, max: 3 }, unit: 'tbsp' }) // [{ type: 'amount', value: '2' }, { type: 'rangeSeparator', value: '–' }, { type: 'amount', value: '3' }, { type: 'literal', value: '\u00A0' }, { type: 'unit', value: 'tbsp' }]
```

Render each part in its own element, with its type in an attribute that your CSS can select, such as `[data-part='unit']`:

QuantityText.tsx
```tsx title="QuantityText.tsx" {7}
import { formatQuantityToParts, type Quantity } from '@recipe-book/core'

export function QuantityText({ quantity }: { quantity: Quantity }) {
  return (
    <span>
      {formatQuantityToParts(quantity).map((part, index) => (
        <span key={index} data-part={part.type}>
          {part.value}
        </span>
      ))}
    </span>
  )
}
```

New part types may appear in a minor release, so style the parts you know and leave the rest as plain text.

## Reference

- [Formatting](https://recipe-book.siraj.page/reference/core/formatting.md) documents every formatting function used here, with its options and rounding rules.
- [Units](https://recipe-book.siraj.page/reference/core/units.md) documents `toSystem`, [`convertTemperature`](https://recipe-book.siraj.page/reference/core/units.md#converttemperature), and the [`Quantity`](https://recipe-book.siraj.page/reference/core/units.md#quantity) type.
- [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md) and [`unknown_unit`](https://recipe-book.siraj.page/errors/unknown_unit.md) explain the errors these functions throw.
