Recipe Book0.6.0

3.4Core reference

Formatting

Reference for the @recipe-book/core functions that format quantities, ingredient lines, servings, yields, temperatures, and durations as text.

§ 3.420 min readView as Markdown

Use these exports from @recipe-book/core to turn quantities, ingredient lines, servings, yields, temperatures, and durations into text for display. Each one that writes a label joins it to the number before it with a no-break space (U+00A0), so a line never breaks between them. The results on this page contain that character, so a test that compares against a regular space doesn’t match. For a walkthrough, see Display quantities. In a React app, import this page’s functions from @recipe-book/react/core. Import your language from @recipe-book/react/core/labels to format with it, and from @recipe-book/react/labels to pass it to the parts, which covers their controls too. The terms of <Recipe.Times> and <Recipe.Nutrition> and the label of <Recipe.CookMode> stay in English unless you set them. Under every pack, <Recipe.Times> writes its durations in English, <Recipe.Nutrition> writes kcal, g, and mg, and the parts show temperatures as °C and °F.

formatQuantity

TypeScript
function formatQuantity(
  quantity: Quantity,
  options?: FormatQuantityOptions,
): string

Formats a quantity as text, such as 1 ½ cups.

Name Type Default Description
quantity Quantity Required The quantity to format.
options FormatQuantityOptions {} The locale, label pack, label length, fractions, and rounding to use.

Returns the rounded amount, a no-break space, and the unit’s label. A range joins its ends with an en dash, and a bare count has no label. When both ends of a range round to the same text, it’s written as one amount, so 1–1.04 cups is 1 cup.

The amount as printed picks the label’s form: singular for 1 and for a fraction below 1, as in ½ cup, and plural otherwise, including an amount that prints as a decimal, and ranges, as in 0.5 cups and ½–1 cups. So 1.04 cups is 1 cup, but 1.04 cups with rounding: 'none'. Many short labels, such as tbsp and g, are the same in both forms. With labels, the label is the pack’s, and the pack’s language picks its form, as LabelWords describes.

By default, rounding is 'kitchen', which rounds each unit to amounts you can measure:

Kitchen rounding
Units Rounds to Quantity Result
tsp, tbsp, cup, fl-oz, pint, quart, gallon, oz, lb, cup-metric, tbsp-au The nearest ⅛ or ⅓, as a fraction 0.3 tbsp ⅓ tbsp
Count units, such as clove, and bare counts The nearest ¼ or ⅓, as a fraction 2.4 2 ⅓
g, ml, cl, dl 1 decimal below 10, and whole numbers from 10 12.5 cL 13 cL
kg, l 2 decimals, or a whole number when 2 would take more than 15 significant digits 1.254 kg 1.25 kg
mg Whole numbers 250.5 mg 251 mg

The metric cup and the Australian tablespoon round like US measures, because cooks measure them with sets of cups and spoons, so half a metric cup is ½ cup, not 0.5 cups. Halfway amounts round up. An amount below the smallest fraction, ⅛ for the units in the first row or ¼ for counts, is written with 1 decimal instead, as in 0.1 tsp. No amount is written as 0: one that would round to 0 gains decimals, so 0.01 tsp stays 0.01 tsp, and 0.047 tsp stays 0.047 tsp, as 0.05 tsp would be written as 0.1 tsp when read back. Trailing zeros are dropped, so 1.5 L isn’t 1.50 L. A quantity you pass as it is, such as 10.1442 tbsp, rounds to 10 ⅛ tbsp, while toSystem lands US volume on a cup or spoon measure first, so 150 mL, which is 10.1442… tbsp, becomes 10 tbsp.

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

formatQuantity({ amount: 1.5, unit: 'cup' }) // '1 ½ cups'
formatQuantity({ amount: { min: 2, max: 3 }, unit: 'tbsp' }) // '2–3 tbsp'
formatQuantity({ amount: 118.29411825, unit: 'ml' }) // '118 mL'
formatQuantity({ amount: 1 / 3, unit: 'cup' }, { fractions: false }) // '0.33 cups'
formatQuantity({ amount: 0.5, unit: 'tsp' }, { unitDisplay: 'long' }) // '½ teaspoon'

Throws a RecipeBookError with one of these codes:

  • invalid_argument when quantity isn’t a quantity object, when the amount isn’t a finite number greater than 0 or a range of them, when a range’s min is greater than its max, when quantity has a max, as a Servings or Yield has, when locale isn’t a language tag that Intl accepts (without Intl, only one that isn’t a string or undefined), when labels isn’t a LabelPack, or when another option isn’t one of its listed values
  • unknown_unit when quantity.unit isn’t a unit ID, such as 'cups'

An error thrown by a getter or proxy in the input or options passes through.

formatQuantityToParts

TypeScript
function formatQuantityToParts(
  quantity: Quantity,
  options?: FormatQuantityOptions,
): QuantityPart[]

Formats a quantity as a list of parts, so you can mark up the amount and the unit separately.

Name Type Default Description
quantity Quantity Required The quantity to format.
options FormatQuantityOptions {} The locale, label pack, label length, fractions, and rounding to use.

Returns an array of QuantityPart objects, in display order. Joining every value gives the text formatQuantity returns for the same arguments.

Part types
type value Where
'amount' An amount, such as '2' First, and again after rangeSeparator
'rangeSeparator' '–', an en dash Between the ends of a range
'literal' '\u00A0', a no-break space Before unit
'unit' A label, such as 'tbsp' Last, when the quantity has a unit

A whole number and a fraction, such as 1 ½, are one amount part, joined by a no-break space. A range whose ends round to the same text has one amount and no rangeSeparator.

TypeScript
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' }]
formatQuantityToParts({ amount: 2 }) // [{ type: 'amount', value: '2' }]

Throws the same errors as formatQuantity.

Display quantities uses it to style the amount and the unit separately.

formatIngredient

TypeScript
function formatIngredient(
  item: {
    ingredient: Ingredient | IngredientLine
    quantity?: Quantity | undefined
  },
  options?: FormatIngredientOptions,
): FormattedIngredient

Formats an ingredient line, such as 3 tbsp butter, melted.

Name Type Default Description
item object Required The Ingredient, or an IngredientLine from parseIngredientLine, to format as ingredient, and optionally a Quantity to show instead of its own as quantity. An item of a resolved recipe has this shape.
options FormatIngredientOptions {} The locale, label pack, label length, fractions, and rounding to use for the quantity, and the system to show a count unit’s size in.

Returns a FormattedIngredient. A line without a quantity is the name and the note alone. When quantity is left out, undefined, or null, the ingredient’s own quantity is used. A falsy quantity, such as 0, NaN, or '', reads as none.

A bare count that takes the plural, such as 2 or 1–2, uses the ingredient’s plural, or its name when the plural is missing, empty, or only whitespace. With labels, the pack’s language picks the form, but the words stay the recipe’s own. In text, the name follows a space after a unit, or a no-break space after a bare count, and the note follows a comma and a space. The line adds nothing for optional: true, so mark optional ingredients in your markup. A name or note keeps any “optional” it has, as in '1 cup flour, optional for dusting'.

A quantity in a count unit, such as a can, package, or stick, gets a size from the ingredient’s mass and volume equivalents, and it follows the quantity in parentheses. A quantity you pass gets a size only in the ingredient’s authored unit, so passing 2 packages for beans authored as 1 can (28 oz) gives 2 packages beans. With system, it’s the first equivalent whose unit belongs to that system, else the first converted into it, in the unit that one item converts to: 2 cans of 28 oz are 794 g each in metric, not 1.59 kg in all. Without system, it’s the first equivalent as authored. The size scales with the quantity, and it’s for the whole count. For a count of exactly 1, it shows as it is: 1 can (28 oz). For any other count, the per-unit size shows, the total divided by the count, then “each”: 2 cans (15 oz each), 1 ½ cans (15 oz each). The per-unit size is clean when the per-unit figure times the count, both as displayed, is within 2% of the total. When it isn’t, the total shows, then “total”: 5 oz over 6 slices displays as ⅞ oz, and 6 × ⅞ oz is 5 ¼ oz, 5% over, so the line reads 6 slices (5 oz total). A count range shows “each” only when every count in the range gives the same displayed per-unit figure, clean at both ends: 2–3 cans (15 oz each) for 30–45 oz, but 2–3 cans (30 oz total) for 30 oz. With labels, the size’s unit takes the pack’s labels, as the quantity’s does, and “each” and “total” are the pack’s size words: 2 Dosen (425 g pro Stück) with de. The size stays in its authored unit, scaled with the count, where dividing it by the count, converting it into system, or multiplying it back by the count would take its amount to Infinity or 0. For a range, its first end decides.

TypeScript
import { formatIngredient, type Ingredient } from '@recipe-book/core'

const butter: Ingredient = {
  id: 'butter',
  name: 'butter',
  quantity: { amount: 3, unit: 'tbsp' },
  note: 'melted',
  equivalents: [],
  optional: false,
}
const egg: Ingredient = {
  id: 'egg',
  name: 'egg',
  plural: 'eggs',
  quantity: { amount: 2 },
  equivalents: [],
  optional: false,
}

formatIngredient({ ingredient: butter }) // { quantity: '3 tbsp', name: 'butter', note: 'melted', text: '3 tbsp butter, melted' }
formatIngredient({ ingredient: egg }).text // '2 eggs'
formatIngredient({ ingredient: egg, quantity: { amount: 1 } }).text // '1 egg'

const tomatoes: Ingredient = {
  id: 'tomatoes',
  name: 'crushed tomatoes',
  quantity: { amount: 1, unit: 'can' },
  equivalents: [{ amount: 28, unit: 'oz' }],
  optional: false,
}
const bacon: Ingredient = {
  id: 'bacon',
  name: 'bacon',
  quantity: { amount: 6, unit: 'slice' },
  equivalents: [{ amount: 5, unit: 'oz' }],
  optional: false,
}

formatIngredient({ ingredient: tomatoes }).text // '1 can (28 oz) crushed tomatoes'
formatIngredient(
  { ingredient: tomatoes, quantity: { amount: 2, unit: 'can' } },
  { system: 'metric' },
).text // '2 cans (794 g each) crushed tomatoes'
formatIngredient({ ingredient: bacon }).size // '5 oz total'

Throws a RecipeBookError with one of these codes:

  • invalid_argument when item isn’t an object whose ingredient has a string name, when the ingredient’s plural or note isn’t a string, for an invalid option even when the item has no quantity, such as a locale that Intl rejects (without Intl, only one that isn’t a string or undefined) or a system other than 'metric' or 'us', or for any other reason formatQuantity gives for a quantity that isn’t falsy or for the size
  • unknown_unit when the quantity’s unit isn’t a unit ID

Only a quantity in the ingredient’s authored count unit reads equivalents, to find the size. Then an equivalents that’s undefined or null reads as none, and a TypeError is thrown for one without a filter method, such as a string or a Set, for an entry that’s undefined or null, and for a size whose amount is missing or null. An entry without a mass or volume unit, such as a string or a number, is skipped. An error thrown by a getter or proxy in the input or options passes through.

Display quantities uses it to list a parsed recipe’s ingredients.

formatServings

TypeScript
function formatServings(
  servings: Servings,
  options?: FormatQuantityOptions,
): string

Formats a recipe’s servings as a number or a range, such as 4–6.

Name Type Default Description
servings Servings Required The servings to format, such as a recipe’s servings or a resolved recipe’s.
options FormatQuantityOptions {} The locale, fractions, and rounding to use. unitDisplay and labels have no effect.

Returns only the number or range, so add the word yourself, as in Serves 4–6 or 4–6 servings. It writes numbers the way formatQuantity writes a bare count.

Scale servings with resolveRecipe.

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

formatServings({ amount: 4, max: 6 }) // '4–6'
formatServings({ amount: 2.5 }) // '2 ½'

Throws a RecipeBookError with the code invalid_argument when servings isn’t an object, when amount isn’t a finite number greater than 0, when max is set and isn’t a finite number greater than amount, when locale isn’t a language tag that Intl accepts (without Intl, only one that isn’t a string or undefined), or when another option isn’t one of its listed values. An error thrown by a getter or proxy in the input or options passes through.

Scale a recipe uses it to show a scaled recipe’s servings.

formatYield

TypeScript
function formatYield(yield_: Yield, options?: FormatQuantityOptions): string

Formats what a batch makes, such as 24 cookies or 2–3 loaves.

Name Type Default Description
yield_ Yield Required The yield to format, such as a recipe’s yield or a resolved recipe’s.
options FormatQuantityOptions {} The locale, label pack, fractions, and rounding to use. unitDisplay has no effect.

Returns the number or range, a no-break space, and the yield’s word. It writes numbers as formatServings does. The number as printed picks the word: unit for 1 and for a fraction below 1, as in ½ loaf, and plural otherwise, including a number that prints as a decimal, and ranges, as in 1 ½ loaves, unless a range’s ends round to the same number, which takes that number’s form, as in 1 loaf for amount: 1 with max: 1.1. So amount: 1.04 is 1 loaf, but 1.04 loaves with rounding: 'none'. Without a plural, or with one that’s empty or only whitespace, the word is always unit, so a yield parsed from text with no other form, such as '2 dozen', keeps its word as written. With labels, the pack’s language picks the form. The word is the recipe’s own, so it’s never translated, whatever the locale or labels.

Scale a yield with resolveRecipe.

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

formatYield({ amount: 24, unit: 'cookie', plural: 'cookies' }) // '24 cookies'
formatYield({ amount: 1, unit: 'loaf', plural: 'loaves' }) // '1 loaf'
formatYield({ amount: 2, max: 3, unit: 'loaf', plural: 'loaves' }) // '2–3 loaves'
formatYield({ amount: 2, unit: 'loaves' }) // '2 loaves'

Throws a RecipeBookError with the code invalid_argument when yield_ isn’t an object, when amount isn’t a finite number greater than 0, when max is set and isn’t a finite number greater than amount, when unit isn’t a string, when plural is set and isn’t a string, when locale isn’t a language tag that Intl accepts (without Intl, only one that isn’t a string or undefined), when labels isn’t a LabelPack, or when another option isn’t one of its listed values. An error thrown by a getter or proxy in the input or options passes through.

Scale a recipe uses it to show a scaled recipe’s yield.

formatTemperature

TypeScript
function formatTemperature(
  temperature: Temperature,
  options?: FormatTemperatureOptions,
): string

Formats a temperature as text, such as 180 °C.

Name Type Default Description
temperature Temperature Required The temperature to format. Its value may be negative.
options FormatTemperatureOptions {} The locale, label pack, label length, and rounding to use.

Returns the rounded value, a no-break space, and the unit’s label: °C or °F, or with unitDisplay: 'long', degrees Celsius or degrees Fahrenheit. The value as printed picks the long label’s form: singular for 1 or -1, so 0.6 °C is 1 degree Celsius, but 0.6 degrees Celsius with rounding: 'none'. With labels, the long label is the pack’s, and the pack’s language picks its form, as in 180 Grad Celsius.

With rounding: 'oven', 350, 375, 400, and 425 °F convert to 180, 190, 200, and 220 °C and back, as on an oven dial.

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

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

formatTemperature(celsius) // '177 °C'
formatTemperature(celsius, { rounding: 'oven' }) // '180 °C'
formatTemperature({ value: 350, unit: 'F' }, { unitDisplay: 'long' }) // '350 degrees Fahrenheit'

Throws a RecipeBookError with the code invalid_argument when the value isn’t a finite number, the unit isn’t 'C' or 'F', locale isn’t a language tag that Intl accepts (without Intl, only one that isn’t a string or undefined), labels isn’t a LabelPack, or another option isn’t one of its listed values. An error thrown by a getter or proxy in the input or options passes through.

Display quantities uses it to round a converted temperature to an oven setting.

formatDuration

TypeScript
function formatDuration(minutes: number, options?: FormatOptions): string

Formats a duration in minutes, such as a recipe’s cook time, as text such as 1 hr 15 min.

Name Type Default Description
minutes number Required The duration in minutes, such as a value from a recipe’s times. It must be 0 or more.
options FormatOptions {} The locale, label pack, and label length to use.

Returns the duration in days, hours, minutes, and seconds, rounded to the second, leaving out parts that are 0. A space separates the parts. The short labels are day or days, hr, min, and sec, and the long labels are day, hour, minute, and second, each with a plural. Days are the largest part, so 2 weeks is 14 days, and a duration that rounds to 0 seconds is 0 min. With labels, the labels are the pack’s, and the pack’s language picks their forms, as in 1 Std. 30 Min.

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

formatDuration(75) // '1 hr 15 min'
formatDuration(1.5) // '1 min 30 sec'
formatDuration(2880, { unitDisplay: 'long' }) // '2 days'
formatDuration(0) // '0 min'

Throws a RecipeBookError with the code invalid_argument when minutes isn’t a finite number 0 or more, locale isn’t a language tag that Intl accepts (without Intl, only one that isn’t a string or undefined), labels isn’t a LabelPack, or unitDisplay isn’t 'short' or 'long'. An error thrown by a getter or proxy in the options passes through.

Display quantities uses it to write a recipe’s times.

Types

FormatOptions

TypeScript
type FormatOptions = {
  locale?: string | undefined
  unitDisplay?: 'short' | 'long' | undefined
  labels?: LabelPack | undefined
}

The options every formatting function takes. Each default is a fixed value, never read from the runtime, so a server and a browser render the same text.

Name Type Description
locale string | undefined A language tag that Intl accepts, such as 'de-DE', for writing numbers. Defaults to 'en-US'. Labels and their plural forms come from labels, and are English without a pack, whatever the locale.
unitDisplay 'short' | 'long' | undefined The label length. Defaults to 'short', which writes tbsp and °C. 'long' writes tablespoons and degrees Celsius.
labels LabelPack | undefined The words to write and the language of their plural forms, such as de from @recipe-book/core/labels. Defaults to English.

For English tags, en alone or with a region such as en-GB, Recipe Book writes numbers itself rather than with Intl, so English output is the same in every runtime. A pack in another language still picks its plural forms with Intl, as LabelWords describes, so with { locale: 'en-US', labels: fr }, 1 ½ pinches is 1 ½ pincée, or 1 ½ pincées in a runtime without Intl or without Intl.PluralRules. Numbers are never grouped, and fractions such as ½ are the same in every locale, so beside one, only the whole number takes the locale’s digits. With fractions: false, every digit does, as the ar-EG lines below show. A tag the runtime doesn’t support falls back to English, but a string Intl rejects throws invalid_argument. Intl rejects 'en_US', and some BCP 47 tags too, such as 'i-klingon' and 'x-private'. In a runtime without Intl, Recipe Book writes English for every string, even 'en_US', and throws for none.

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

formatQuantity({ amount: 2.5, unit: 'g' }, { locale: 'de-DE' }) // '2,5 g'
formatQuantity({ amount: 1.5, unit: 'cup' }, { locale: 'de-DE' }) // '1 ½ cups'
formatQuantity({ amount: 1500, unit: 'g' }, { locale: 'de-DE' }) // '1500 g'
formatQuantity({ amount: 6.25, unit: 'cup' }, { locale: 'ar-EG' }) // '٦ ¼ cups'
formatQuantity({ amount: 6.25, unit: 'cup' }, { locale: 'ar-EG', fractions: false }) // '٦٫٢٥ cups'

labels sets the words and locale sets the numbers, so pass both: with labels alone, the numbers are English. The pack’s language picks each label’s form, as LabelWords describes:

TypeScript
import { formatQuantity } from '@recipe-book/core'
import { de, fr } from '@recipe-book/core/labels'

const pinches = { amount: 1.5, unit: 'pinch' } as const

formatQuantity(pinches, { locale: 'de-DE', labels: de, fractions: false }) // '1,5 Prisen'
formatQuantity(pinches, { locale: 'fr-FR', labels: fr, fractions: false }) // '1,5 pincée'
formatQuantity(pinches, { labels: de, fractions: false }) // '1.5 Prisen'

Display quantities uses these options to spell out a unit and to write German numbers, and Localize recipes uses labels to write German labels.

FormatQuantityOptions

TypeScript
type FormatQuantityOptions = FormatOptions & {
  fractions?: boolean | undefined
  rounding?: 'kitchen' | 'none' | undefined
}

The options for formatQuantity, formatQuantityToParts, formatIngredient, formatServings, and formatYield: the FormatOptions, and these.

Name Type Description
fractions boolean | undefined Whether to write cups, spoons, the other units in the first row of the rounding table, and counts as fractions, such as 1 ½. Defaults to true. false writes up to 2 decimals instead, such as 1.5, and a whole number when 2 would take more than 15 significant digits. It still rounds to the nearest ⅛ or ⅓ first, or ¼ or ⅓ for counts, so 1.2 cups is 1.25 cups, and an amount below the smallest of those gets 1 decimal, as with true, or more when it would round to 0, so 0.06 cups is 0.1 cups. g, kg, mg, mL, cL, dL, and L always use decimals.
rounding 'kitchen' | 'none' | undefined Defaults to 'kitchen', which rounds each unit to amounts you can measure, as formatQuantity lists. 'none' writes every unit with up to 3 decimals, or more for an amount that would round to 0, and a whole number when 3 would take more than 15 significant digits.

Display quantities uses fractions to write decimals.

FormatIngredientOptions

TypeScript
type FormatIngredientOptions = FormatQuantityOptions & {
  system?: System | undefined
}

The options for formatIngredient: system, and the FormatQuantityOptions.

Name Type Description
system System | undefined The system to show a count unit’s size in, such as a resolved recipe’s system. Without it, the size shows as authored. It has no effect on the quantity, which shows as it’s passed.

Show the size of a can passes the reader’s system.

QuantityPart

TypeScript
type QuantityPart = {
  type: 'amount' | 'rangeSeparator' | 'unit' | 'literal'
  value: string
}

One piece of a formatted quantity, from formatQuantityToParts. Unlike the parts from Intl.NumberFormat, a range’s dash is its own rangeSeparator part.

Name Type Description
type 'amount' | 'rangeSeparator' | 'unit' | 'literal' What the piece is, as formatQuantityToParts lists. It may gain members in a minor release, so give a switch on it a default case.
value string The piece’s text, such as '2' or 'tbsp'.

Display quantities puts each part’s type in an attribute that CSS can select.

FormatTemperatureOptions

TypeScript
type FormatTemperatureOptions = FormatOptions & {
  rounding?: 'kitchen' | 'oven' | 'none' | undefined
}

The options for formatTemperature: the FormatOptions, and this.

Name Type Description
rounding 'kitchen' | 'oven' | 'none' | undefined Defaults to 'kitchen', which writes whole degrees. 'oven' rounds to the nearest 10 °C or 25 °F. 'none' writes up to 3 decimals, and a whole number when 3 would take more than 15 significant digits.

Display quantities uses rounding: 'oven' for a converted oven temperature.

FormattedIngredient

TypeScript
type FormattedIngredient = {
  quantity?: string | undefined
  size?: string | undefined
  name: string
  note?: string | undefined
  text: string
}

An ingredient line from formatIngredient, in pieces for markup and as one line.

Name Type Description
quantity string | undefined The quantity, as formatQuantity formats it. Absent for a line without one.
size string | undefined The size that text shows in parentheses, as formatIngredient describes. Absent when the quantity has no size.
name string The ingredient’s name, or its plural when a bare count takes the plural, as in 2 eggs.
note string | undefined The ingredient’s note, such as melted. Absent when it has none.
text string The whole line: the quantity, any size in parentheses, the name, and the note after a comma, as in 3 tbsp butter, melted.

Display quantities prints each ingredient’s text.

Contents