DEV Community

eth shihao
eth shihao

Posted on

FDA Nutrition Facts rounding in JavaScript, benchmarked at the cutoffs

A serving measured at 142.5 mg sodium prints 140 mg. At 145 mg, it prints 150 mg. Both amounts are above the 140 mg cutoff, so the label uses 10 mg increments. A formatter hardwired to 5 mg increments prints 145 mg for the first serving. That one fixture catches a rule a generic decimal formatter misses. 21 CFR 101.9(c)(4)

Keep three values in the label record

At 1.49 g added sugars, the amount line displays 1 g. The percentage can be 3% using the measured amount or 2% using the declared amount. Both percentages derive from the 50 g Daily Value. A label record that stores only { amount: 1, dailyValue: 3 } loses the numerator and makes the proof hard to reproduce. Persist the measurement, the declaration, and the percentage basis. 21 CFR 101.9(d)(7)(ii) and FDA Daily Value reference

Measured per serving Amount %DV in this fixture What the case exercises
4.999999 kcal 0 — Select the permitted zero declaration before rounding
55 kcal 60 — Switch from 5- to 10-Calorie increments above 50
0.499999 g total fat 0 1% The measured numerator stays available after the amount rounds to zero
142.5 mg sodium 140 6% Use the upper increment from the measured amount
2 mg cholesterol <5 1% Preserve the less-than declaration as text
0.75 g added sugars <1 2% Compute a percentage without assigning a number to the less-than declaration
1.49 g added sugars 1 3% or 2% Record which numerator produced the percentage

The library uses integer millionths of the input unit. For a nonnegative amount represented by BigInt units and an increment represented by BigInt step, ((2n * units + step) / (2n * step)) * step rounds to that increment with ties upward. Choose the amount rule before running that expression. The output model leaves a declared-basis percentage empty when the declaration is a less-than string.

Run the boundary benchmark

The comparator uses one fixed increment per nutrient and calculates every available percentage from the measured amount. The score counts exact matches of the amount string and percentage together. The timing loop measures the reference implementation separately and includes parsing, rule selection, and result allocation. Run this from the checkout root with Node.js 20+. MIT source and test suite

import assert from 'node:assert/strict';
import { performance } from 'node:perf_hooks';
import { roundNutrient } from './src/index.js';

// key, measured input, expected amount, expected %DV, alternate basis
const cases = [
  ['calories', '4.999999', '0', null],
  ['calories', '5', '5', null],
  ['calories', '50.000001', '50', null],
  ['calories', '55', '60', null],
  ['totalFat', '0.499999', '0', 1],
  ['totalFat', '4.75', '5', 6],
  ['totalFat', '5.5', '6', 7],
  ['sodium', '137.5', '140', 6],
  ['sodium', '142.5', '140', 6],
  ['sodium', '145', '150', 6],
  ['cholesterol', '2', '<5', 1],
  ['addedSugars', '0.75', '<1', 2],
  ['addedSugars', '1.49', '1', 3],
  ['addedSugars', '1.49', '1', 2, 'declared'],
];

const fixedRules = {
  calories: [5, null], totalFat: [0.5, 78], sodium: [5, 2300],
  cholesterol: [5, 300], addedSugars: [1, 50],
};
function fixedStep(key, measured) {
  const [step, dv] = fixedRules[key];
  const raw = Number(measured);
  return [String(Math.round(raw / step) * step), dv === null ? null : Math.round(raw * 100 / dv)];
}

let fixedMatches = 0;
for (const [key, measured, amount, dv, dvBasis] of cases) {
  const result = roundNutrient(key, measured, { dvBasis });
  assert.deepEqual([result.amount, result.percentDailyValue], [amount, dv], `${key} ${measured}`);
  const [fixedAmount, fixedDv] = fixedStep(key, measured);
  if (fixedAmount === amount && fixedDv === dv) fixedMatches++;
}

let checksum = 0;
function exercise(repeats) {
  const start = performance.now();
  for (let repeat = 0; repeat < repeats; repeat++) {
    for (const [key, measured, , , dvBasis] of cases) {
      const result = roundNutrient(key, measured, { dvBasis });
      checksum += result.percentDailyValue ?? 0;
    }
  }
  return performance.now() - start;
}
exercise(2000);
const repeats = 10_000;
const times = Array.from({ length: 9 }, () => exercise(repeats)).sort((a, b) => a - b);
console.log({
  node: process.version, referenceMatches: cases.length, fixedMatches,
  callsPerTrial: repeats * cases.length, medianMs: Number(times[4].toFixed(1)), checksum,
});
Enter fullscreen mode Exit fullscreen mode

On an Apple M1 Pro with Node.js v24.15.0, the reference matched 14/14 boundary fixtures and the fixed-step comparator matched 5/14. The reference median was 162.5 ms for 140,000 calls across nine trials after warmup. The checksum was 3,680,000. The cases deliberately cluster around cutoffs, so the match rates describe this fixture set. Timing includes the full reference call and will vary by machine.

Reconcile the printable proof

Compare the measured and declared basis on the same sample. Next, change the printed %DV from 3 to 2 and watch the validator report the mismatch. The checker implements one display policy for the standard U.S. label for adults and children aged four and older. Alternate permitted declarations, claim eligibility, and full panel review remain separate decisions. Open the browser validator

Once the percentage and amount agree with your calculation record, compare them with the final artwork at its printed size. NutritionLabelPack

Disclosure. The publisher operates NutritionLabelPack. The draft was generated with AI and the benchmark was run locally.

Top comments (0)