Dev.to WebDev ๐Ÿ›  Dev ๐Ÿ‘ 0 ๐Ÿ“– 15 min read

The Deurenberg BMI-to-Body-Fat Formula in JavaScript: How to Implement It, and When Not to Trust It

If you have built a BMI calculator, the next feature request is almost always "can it show body fat too?" The usual answer, in tutorials, fitness apps and Stack Overflow snippets, is a single line of arithmetic: the Deur

The Deurenberg BMI-to-Body-Fat Formula in JavaScript: How to Implement It, and When Not to Trust It

If you have built a BMI calculator, the next feature request is almost always "can it show body fat too?" The usual answer, in tutorials, fitness apps and Stack Overflow snippets, is a single line of arithmetic: the Deurenberg formula, which turns BMI, age and sex into an estimated body fat percentage.

It is a real, peer-reviewed equation, and implementing it takes about thirty seconds. Implementing it responsibly takes a bit longer. The formula was fitted to a specific group of people, it has a published error of about four percentage points, it was never meant for children, and it knows nothing about muscle. None of that is visible in the one-liner.

This post covers both halves: a small, framework-free JavaScript module for the Deurenberg body fat formula, the input validation and refusals it needs, a node --test suite with hand-checked golden values, and the labeling rules that keep the UI from claiming more than the math supports. Nothing here is medical advice. The output is an estimate, and I will keep saying so, because your UI should too.

What people are actually asking

Before writing code, I looked at where this formula comes up and what goes wrong.

On the fitness side of Reddit, the formula gets passed around as "the Wikipedia formula" for body fat, usually with a caveat that it is rough. The more interesting threads are the ones where someone pushes on it. In one r/Fitness thread, a 36-year-old man at 5'7.5" and 140 lb plugged himself in, got about 18%, then solved the equation backwards for 13% and got a target weight of 113 lb, which he rightly found absurd. I re-ran his numbers: his arithmetic is correct (BMI 21.6, estimate 18.0%; 13% needs a BMI of about 17.4, roughly 51 kg). The problem was not the arithmetic. One reply summed it up: it is "a simple regression equation... It's useless for individuals, all it shows is trends in datasets." A similar 2015 thread did the same inversion for a 15% goal, and a commenter there reported that the formula put them near 19% when a bone-density scan a few weeks earlier had said 14%. That is one person's report, not a study, but it is exactly the kind of gap the paper's error term predicts.

On the developer side, the formula shows up in class projects. A 2019 r/learnprogramming post about a C# BMI and body fat calculator is a good catalogue of small, shippable mistakes: the child branch used 1.52 ร— BMI where the paper says 1.51, the child/adult split was age < 18 while the paper splits at 15 and 16, the BMI label was formatted with a trailing %, and the actual crash was the page parsing an empty age field on load.

On X, the formula is shared as a rule of thumb in several languages, and indie app builders list "body fat percentage calculator" as the next feature after BMI. One privacy-focused browser-tool account pointed out that two people with the same BMI can be 22 body-fat points apart under this formula. That checks out, and it makes a great test: a 70-year-old woman and a 20-year-old man at the same BMI always differ by 0.23 ร— 50 + 10.8 = 22.3 points.

So the questions are consistent: Is this formula right? Why does it give me a weird number? Can I use it to set a goal? The code below answers the first, explains the second, and refuses the third.

The formula, from the paper

The source is Deurenberg, Weststrate and Seidell, "Body mass index as a measure of body fatness: age- and sex-specific prediction formulas," British Journal of Nutrition 65 (1991): 105โ€“114. I read the full text rather than trusting a calculator site. For adults (16 and older in the paper):

BF% = 1.20 ร— BMI + 0.23 ร— age โˆ’ 10.8 ร— sex โˆ’ 5.4      (sex: male = 1, female = 0)

For children (15 and younger) the paper gives a different equation:

BF% = 1.51 ร— BMI โˆ’ 0.70 ร— age โˆ’ 3.6 ร— sex + 1.4

A few details from the paper matter for implementation:

  • The sample. 1,229 healthy volunteers measured in Wageningen, the Netherlands (521 men, 708 women), aged 7 to 83, with BMI from 13.9 to 40.9. Body fat was measured by underwater weighing. The adult equation was fitted on the roughly 750 participants aged 16 and over.
  • The error. The adult equation explains 79% of the variance with a standard error of estimate (SEE) of 4.1 body-fat percentage points. The child equation explains only 38%, and the authors themselves write that "it may be questioned whether the BMI is a valid determinant for BF% in children."
  • High BMI. In participants with obesity the equation slightly overestimated body fat, and the difference became statistically significant at a BMI of 33 or more.
  • Uneven fit by age. The correlation between BMI and body fat was strongest in adults aged 26 to 35 and weakest in boys aged 16 to 20 and men 66 and older. The oldest age group had only 29 men and 21 women.

The coefficients themselves tell you how the model behaves: each BMI point adds 1.2 percentage points, each year of age adds 0.23, and being coded male subtracts 10.8. That is all it knows.

Deurenberg body fat formula in JavaScript: estimated body fat percentage plotted against BMI from 17 to 40 for women and men aged 25 and 65, showing four parallel straight lines, a 10.8-point gap between sexes, a ยฑ4.1-point error band, and the BMI 30-plus zone where the 1991 paper reports slight overestimation
The Deurenberg body fat formula is four parallel straight lines. The shaded band is one standard error of estimate (ยฑ4.1 points), which is wider than the gap between many "categories" people care about.

The module

Here is the whole thing. The bare equation is one function; everything else is about deciding whether to show its result.

// deurenberg.mjs โ€” adult BMI-based body-fat ESTIMATE (Deurenberg, Weststrate & Seidell, 1991)
export const LB_TO_KG = 0.45359237; // exact, by definition
export const IN_TO_M = 0.0254;      // exact, by definition

export const STUDY = Object.freeze({
  adultMinAge: 16, maxAge: 83,   // adult equation: age >= 16; oldest participant 83
  minBmi: 13.9, maxBmi: 40.9,    // BMI range of the sample
  see: 4.1,                      // standard error of estimate, BF% points
});

const SEX_CODE = Object.freeze({ male: 1, female: 0 });

export function toMeters({ cm, ft = 0, inches = 0 }) {
  if (cm != null) return cm / 100;
  return (ft * 12 + inches) * IN_TO_M;
}

export function toKg({ kg, lb }) {
  return kg != null ? kg : lb * LB_TO_KG;
}

export function bmi(kg, m) {
  if (!Number.isFinite(kg) || kg <= 0) throw new RangeError(`weight must be > 0 kg, got ${kg}`);
  if (!Number.isFinite(m) || m <= 0 || m > 3) throw new RangeError(`height must be in meters (0โ€“3], got ${m}`);
  return kg / (m * m);
}

/** The bare equation. No validation: use estimateBodyFat() in UI code. */
export function deurenbergAdult(bmiValue, age, sexCode) {
  return 1.2 * bmiValue + 0.23 * age - 10.8 * sexCode - 5.4;
}

export function estimateBodyFat({ weight, height, age, sex }, { minAge = 18 } = {}) {
  const sexCode = SEX_CODE[sex];
  if (sexCode === undefined) {
    throw new TypeError(`sex must be "male" or "female" (the formula's coding), got ${JSON.stringify(sex)}`);
  }
  if (!Number.isFinite(age) || age < 0 || age > 120) {
    throw new RangeError(`age must be a number of years in [0, 120], got ${age}`);
  }
  const b = bmi(toKg(weight), toMeters(height));

  if (age < Math.max(minAge, STUDY.adultMinAge)) return { ok: false, reason: "under-adult-age", bmi: b };
  if (b < 10 || b > 80) return { ok: false, reason: "implausible-bmi", bmi: b };

  const raw = deurenbergAdult(b, age, sexCode);
  const warnings = [];
  if (b < STUDY.minBmi || b > STUDY.maxBmi) warnings.push("bmi-outside-study-range");
  if (age > STUDY.maxAge) warnings.push("age-outside-study-range");
  if (b >= 30) warnings.push("may-overestimate-at-high-bmi");
  if (raw < 2) warnings.push("implausibly-low-result");

  return {
    ok: true,
    kind: "estimate",
    method: "Deurenberg 1991 (BMI, age, sex)",
    bmi: b,
    raw,
    display: Math.round(raw),                         // whole percent: SEE is ~4 points
    band: [Math.round(raw - STUDY.see), Math.round(raw + STUDY.see)],
    warnings,
  };
}

export function formatEstimate(r) {
  if (!r.ok) return "Not available for this input";
  return `Estimated body fat โ‰ˆ ${r.display}% (typical error ยฑ4 points: ${r.band[0]}โ€“${r.band[1]}%)`;
}

Design decisions, one at a time

Units go in once, at the edge. The formula needs BMI in kg/mยฒ, so pounds and feet-and-inches are converted with the exact definitions (1 lb = 0.45359237 kg, 1 in = 0.0254 m) before anything else happens. The bmi() guard rejects a height above 3 m, which catches the most common unit bug of all: passing centimeters where meters are expected.

Sex is an explicit string, not a boolean. The paper codes men as 1 and women as 0. If your function takes isMale or gender: 0|1, somebody will eventually pass the opposite convention and shift every result by 10.8 points with no error. Mapping "male"/"female" to the coefficient inside the module, and throwing on anything else, removes that whole class of bug. It also lets the UI label the field honestly. Body Visualizer's own calculator calls it "Sex used by the formula," which is the accurate description: it is a regression coefficient, not a statement about anyone's identity.

Three kinds of "no." Bad input that indicates a bug (NaN, a negative age, a weight of zero, the wrong sex code) throws, because that is a programming error. Input that is valid but outside what the formula covers refuses with { ok: false, reason }, so the UI can explain why there is no number. Input inside the formula's reach but at its edges warns, so the UI can add context next to the number.

Adults only, with a policy floor. The adult equation was fitted on people 16 and older, so the module never applies it below 16, no matter what you pass. On top of that, minAge defaults to 18, because most consumer apps define adulthood that way (CDC's adult BMI calculator starts at 20; pick the floor that matches the rest of your product). I deliberately did not implement the child equation. Its explained variance is 38%, its own authors question whether BMI is a valid predictor of body fat in children, and pediatric weight status is normally assessed with age- and sex-specific BMI percentiles instead. Refusing is the honest output.

Warnings come from the paper, not from vibes. BMI outside 13.9 to 40.9 and age over 83 are outside the sample the equation was fitted on, so the result is an extrapolation. At a BMI of 30 or more, the paper itself reports overestimation. These are facts about the formula you can show beside the number.

Round once, and round coarsely. With a standard error of about four points, a display like "23.47%" is fake precision. The module keeps the raw value for tests and charts, and gives the UI a whole-number display and a one-SEE band. If the residuals are roughly normal, about two in three adults in a population like the study's would fall inside that band, which means one in three would not. That is worth knowing before you put a decimal point on it.

Tests with golden values you computed by hand

The most useful tests for a formula are values you did not get from the code under test. For a linear equation, pencil arithmetic is enough:

  • Woman, BMI 22, age 30: 26.4 + 6.9 โˆ’ 0 โˆ’ 5.4 = 27.9
  • Man, BMI 22, age 30: 26.4 + 6.9 โˆ’ 10.8 โˆ’ 5.4 = 17.1
  • Woman, BMI 30, age 60: 36.0 + 13.8 โˆ’ 5.4 = 44.4
  • Man, BMI 25, age 45: 30.0 + 10.35 โˆ’ 10.8 โˆ’ 5.4 = 24.15

A confession that doubles as an argument for this practice: for the end-to-end case (70 kg, 175 cm, age 40, female) I first wrote 33 in the test. The test failed. The correct value is BMI 22.857, so 27.43 + 9.2 โˆ’ 5.4 = 31.23, which displays as 31. The code was right and my head was wrong, and the only reason I know is that the expected value was written down independently.

import { test } from "node:test";
import assert from "node:assert/strict";
import { deurenbergAdult, estimateBodyFat, formatEstimate, bmi } from "./deurenberg.mjs";

const close = (a, b, eps = 1e-9) =>
  assert.ok(Math.abs(a - b) <= eps, `${a} is not within ${eps} of ${b}`);

test("golden values from hand arithmetic", () => {
  close(deurenbergAdult(22, 30, 0), 27.9);
  close(deurenbergAdult(22, 30, 1), 17.1);
  close(deurenbergAdult(30, 60, 0), 44.4);
  close(deurenbergAdult(25, 45, 1), 24.15);
});

test("coefficients: +1 BMI = +1.2, +1 year = +0.23, male = -10.8", () => {
  close(deurenbergAdult(23, 30, 0) - deurenbergAdult(22, 30, 0), 1.2);
  close(deurenbergAdult(22, 31, 0) - deurenbergAdult(22, 30, 0), 0.23);
  close(deurenbergAdult(22, 30, 1) - deurenbergAdult(22, 30, 0), -10.8);
});

test("same BMI, 70 y woman vs 20 y man: always 22.3 points apart", () => {
  for (const b of [18.5, 22, 27, 35]) {
    close(deurenbergAdult(b, 70, 0) - deurenbergAdult(b, 20, 1), 22.3);
  }
});

test("70 kg, 175 cm, 40 y female: BMI 22.857 -> 31.23 -> displays 31", () => {
  const r = estimateBodyFat({ weight: { kg: 70 }, height: { cm: 175 }, age: 40, sex: "female" });
  assert.equal(r.display, 31);
  assert.deepEqual(r.band, [27, 35]);
  assert.match(formatEstimate(r), /^Estimated body fat โ‰ˆ 31%/);
});

test("refuses under-18 by default and under-16 always", () => {
  const teen = { weight: { kg: 55 }, height: { cm: 165 }, age: 15, sex: "male" };
  assert.equal(estimateBodyFat(teen).reason, "under-adult-age");
  assert.equal(estimateBodyFat({ ...teen, age: 17 }, { minAge: 16 }).ok, true);
  assert.equal(estimateBodyFat({ ...teen, age: 15 }, { minAge: 0 }).ok, false);
});

test("rejects bad input loudly", () => {
  const base = { weight: { kg: 70 }, height: { cm: 175 }, age: 30, sex: "female" };
  assert.throws(() => estimateBodyFat({ ...base, sex: 1 }), TypeError);
  assert.throws(() => estimateBodyFat({ ...base, age: NaN }), RangeError);
  assert.throws(() => bmi(70, 175), RangeError); // cm passed as m
});

The full file in the repo has ten tests, including a metric/imperial identity test (the same body entered in kilograms and centimeters or in pounds and inches must produce the same raw estimate), a monotonicity sweep (more weight at fixed height, age and sex must never lower the estimate), warning checks for an age of 90 and a BMI above 40.9, and exact-constant checks for the unit helpers. All ten pass with node --test on Node 24.

Here is why each group earns its place:

  1. Golden values pin the coefficients. A typo like the 1.52 in that class project fails immediately.
  2. Coefficient tests document the model in executable form. If someone "improves" the formula with a different source's constants, these tell them exactly what changed.
  3. The 22.3-point invariant is a property test that holds at every BMI. It catches a flipped sex code, which a single golden value at one BMI might not make obvious.
  4. Identity and monotonicity catch unit bugs and sign errors, the same way they do for plain BMI.
  5. Refusals and throws are tested as first-class behavior, because a calculator that shows "Body fat: 12%" for a 15-year-old, or "NaN%" for an empty field, is worse than one that shows nothing.

Deurenberg body fat formula in JavaScript validation flow: normalize units and sex coding, throw on invalid input or refuse for under-18, under-16 and implausible BMI, compute and warn outside the study's BMI 13.9 to 40.9 and age 83 range or at BMI 30 and above, then round to a whole percent and label as an estimate with a plus or minus 4 point band
Implementing the Deurenberg body fat formula in JavaScript is one line of math and three layers of deciding when not to show it.

When not to trust it

The paper is careful about its limits; most implementations drop them. These are the ones that should shape your UI.

Muscle. BMI is weight over height squared. CDC states it plainly: "BMI does not distinguish between fat, muscle, and bone mass." The Deurenberg formula inherits that blindness. Someone who carries a lot of muscle for their height gets a high BMI, and the formula converts that into a high body-fat estimate. This is the most common complaint in the fitness threads, and it is correct. If your audience includes people who strength-train, a BMI-based estimate should be shown as a population average for their inputs, not as a reading of their body.

Population. The equation was fitted on adults measured in the Netherlands. Paul Deurenberg's own later work found that the relationship between BMI and body fat differs between ethnic groups: a 1998 meta-analysis with Yap and van Staveren found differences of up to several BMI units at the same body fat, age and sex, and a 2002 review reported that Asian populations studied generally had 3 to 5 percentage points more body fat than Caucasians at the same BMI. If you ship this formula globally, the honest thing is to say whose data it came from.

Age. Age is a linear term, so the formula assumes body fat at a given BMI rises by exactly 0.23 points a year, forever. The fit was weakest in the oldest men and the youngest adult men, and the sample had very few people over 65. Beyond 83 you are extrapolating. A related product wrinkle: if your tool does not ask for age and assumes a default, say so. Body Visualizer's 3D body visualizer, for example, assumes age 30 for its Deurenberg-based estimate; at the same BMI, someone aged 60 would get a figure 6.9 points higher. That is fine as long as the label says what was assumed.

High BMI. The paper reports overestimation in participants with obesity, significant from a BMI of 33. Show the warning there rather than in a footnote.

Individuals versus populations. A regression line describes how body fat varied with BMI, age and sex across people. It does not describe what happens to one person who changes. That is why inverting it to compute a "goal weight" produces numbers like 113 lb: it treats a lighter you as an average, different person at that lower BMI, whose lean mass is lower too. Do not offer a "target body fat โ†’ target weight" feature built on this formula. If you need a target calculation, base it on an explicit body-composition assumption, such as holding lean mass constant, and state that assumption on screen.

Labeling it in the UI

Once the math and validation are in place, the remaining work is words:

  • Call it an estimate, every time. "Estimated body fat โ‰ˆ 31%" is the label, not "Body fat: 31.2%." The kind: "estimate" field in the return value exists so the rendering layer can never forget.
  • Show the band. One standard error (ยฑ4 points) next to the number teaches more about the method than any disclaimer paragraph.
  • Name the method and the source. "BMI-based (Deurenberg et al., 1991)" lets an interested user look it up and lets a skeptical one discount it.
  • Put limits next to the number. "Does not account for muscle mass" belongs beside the result, not in a terms page.
  • No verdicts. Avoid red/green gauges and health judgments. The formula estimates a percentage; it does not diagnose anything, and your product should not imply it does.
  • Keep it local. The inputs are four numbers the user already typed. There is no reason to send them to a server to multiply them by 1.2.

For a reference implementation of most of these choices, Body Visualizer's body fat calculator puts the BMI-based estimate next to a Navy tape-measure estimate, limits it to adults, keeps calculations in the browser, and states that the two methods "cannot validate each other." That last line is a good model for any app showing two estimates side by side. If you want to see why a single percentage says little about shape, its body fat visualizer maps an entered percentage onto a 3D reference model. That model is an illustration, not a scan, and the same honesty applies: arithmetic from entered numbers is exact, while anything drawn from them is an estimate.

Recap

  • The adult Deurenberg formula is 1.20 ร— BMI + 0.23 ร— age โˆ’ 10.8 ร— sex โˆ’ 5.4, with male = 1 and female = 0, from a 1991 study of volunteers in the Netherlands, with a 4.1-point standard error.
  • Convert units once, encode sex explicitly, and throw on input that indicates a bug.
  • Refuse under 16 always and under your adult policy age by default; do not ship the child equation.
  • Warn outside the study's BMI and age range and at a BMI of 30 or more.
  • Round to a whole percent and show a ยฑ4-point band.
  • Test with hand-computed golden values, coefficient checks, the 22.3-point invariant, unit identity and monotonicity.
  • Do not invert it into a goal-weight calculator, and label every result as an estimate.

The formula is one line. The judgment about when to show it is the feature.

Sources

๐Ÿ“ฐ Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.