Implement BMI, Waist-to-Height and Waist-to-Hip Ratio in JavaScript (and Unit-Test Them Against CDC Numbers)
BMI, waist-to-height ratio (WHtR) and waist-to-hip ratio (WHR) are three of the most common "health metrics" developers get asked to add to an app. Each formula fits on one line. And yet a BMI calculator is one of the mo
BMI, waist-to-height ratio (WHtR) and waist-to-hip ratio (WHR) are three of the most common "health metrics" developers get asked to add to an app. Each formula fits on one line. And yet a BMI calculator is one of the most common practice projects people post about, and the questions that follow are remarkably consistent: why is my imperial result in the thousands, why does 24.95 show up as 24.9, and why does my metric answer differ from my imperial one?
This post is a practical implementation guide for all three metrics in plain JavaScript, plus the small test suite that keeps them honest. The code is framework-free, runs in Node 20+ or the browser, and every "golden value" in the tests comes from a public CDC or NICE example rather than from my own calculator checking itself.
A quick scope note before the code: these are adult screening metrics. They are arithmetic from the numbers a user types in, not a diagnosis, and your UI should say so. I will come back to labeling at the end, because it is as much a part of shipping this feature as the math.
What people actually get wrong
Before writing a line, I looked at where people get stuck. A few patterns repeat across Reddit and X:
-
Feet where the formula expects inches. In one r/learnprogramming thread, a learner entered a height of
5.5into thelb Γ 703 Γ· inΒ²formula and got a BMI in the thousands. The replies were immediate: the formula is for inches, and 5.5 feet is not the same thing as 5 ft 5 in anyway. -
Rounding in the middle of the calculation. The same snippet called
.toFixed(2)on the height inside the expression, so a string was being squared and the precision was being thrown away before the division. -
Floating-point display surprises. An r/learnjavascript question asked why a carefully rounded value printed as
52.949999999999996. The answers coveredtoFixed,Number.EPSILON, and integer math. All of them apply to BMI. - Unit switching is "the tricky part." On X, developers shipping portfolio BMI calculators keep calling out the metric/imperial toggle as the hardest bit, and some tool listings even describe imperial input as "lb/ft," which is a different formula from the one CDC publishes.
-
Mixed constants. One r/javahelp health calculator computed BMI as
weight * 4.88 / (height / 12)Β², which is the pounds-per-square-foot version of the constant, while the same class used inches everywhere else. It works, until somebody "fixes" one side.
None of these are hard bugs. They are just easy to ship, and they all disappear if you structure the code in four stages: normalize, compute, round once, label.

BMI, WHtR and WHR in JavaScript as one four-stage pipeline. Each stage is a place a specific class of bug lives.
The formulas, from the sources
BMI. CDC defines adult BMI as weight in kilograms divided by height in meters squared. For U.S. customary units, CDC publishes weight (lb) Γ· height (in)Β² Γ 703. That 703 is a rounded conversion factor: one pound is exactly 0.45359237 kg and one inch is exactly 0.0254 m, so the exact factor is about 703.07. The difference almost never changes a value rounded to one decimal, but it is a good reason to convert to SI once and use a single formula instead of maintaining two.
Waist-to-height ratio. NICE's overweight and obesity guideline tells people to measure waist and height in the same unit and divide one by the other. Its own worked examples are 96.5 cm Γ· 170 cm and 38 in Γ· 67 in, both giving 0.57. NICE classifies 0.4 to 0.49 as healthy central adiposity, 0.5 to 0.59 as increased, and 0.6 or more as high, for adults with a BMI under 35, and it phrases the message as "keep your waist to less than half your height."
Waist-to-hip ratio. WHR is waist circumference divided by hip circumference, again in the same unit. The WHO expert consultation report on waist circumference and waist-hip ratio lists 0.90 or more for men and 0.85 or more for women as "substantially increased" risk of metabolic complications, and it notes that cut-offs may differ between populations.
Notice what the two ratios have in common: they are unitless. You do not need to convert the waist to meters before dividing by height in meters. You only need both numbers in the same unit. That is a test case, not just a remark.
The module
Here is the whole thing. It is short on purpose.
// metrics.mjs β adult BMI, waist-to-height and waist-to-hip ratio
export const LB_TO_KG = 0.45359237; // exact, by definition
export const IN_TO_M = 0.0254; // exact, by definition
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;
}
function assertPositive(name, v) {
if (!Number.isFinite(v) || v <= 0) {
throw new RangeError(`${name} must be a positive number, got ${v}`);
}
}
export function bmi(weightKg, heightM) {
assertPositive("weightKg", weightKg);
assertPositive("heightM", heightM);
if (heightM > 3) throw new RangeError("heightM looks like centimeters");
return weightKg / (heightM * heightM);
}
// Round half away from zero to 1 decimal, using an integer step
// so 24.95 does not become 24.9 the way (24.95).toFixed(1) does.
export function round1(x) {
return Math.sign(x) * Math.round(Math.abs(x) * 10 + 1e-9) / 10;
}
export function bmiCategory(bmiValue) {
const b = round1(bmiValue); // categorize the number you display
if (b < 18.5) return "underweight";
if (b < 25) return "healthy";
if (b < 30) return "overweight";
return "obesity";
}
export function ratio(part, whole) {
assertPositive("part", part);
assertPositive("whole", whole);
return part / whole;
}
export const waistToHeight = (waist, height) => ratio(waist, height); // same unit
export const waistToHip = (waist, hip) => ratio(waist, hip); // same unit
A few decisions worth explaining.
Height is a structured value, not a number. toMeters({ ft: 5, inches: 9 }) makes it impossible to pass 5.9 and mean "five foot nine." If your form has a single imperial height field, parse it into feet and inches at the edge of the app and reject anything ambiguous. The r/learnprogramming bug above is exactly this: a number that looked like a height but was in the wrong unit.
Validation throws instead of returning NaN. An empty input parsed with Number("") is 0, and 0 divided by a squared height is a perfectly valid-looking BMI of zero. Throwing a RangeError for non-finite, zero, or negative values means your UI has to decide what to show, instead of silently rendering nonsense. The heightM > 3 guard catches the very common "I passed 175 instead of 1.75" mistake.
No rounding until the end. bmi() returns full precision. Rounding belongs to presentation, and doing it once avoids compounding errors. If you need to show the user their value in two units, convert from the unrounded value both times.
The rounding trap that CDC's own table exposes
This is the part most BMI calculators get subtly wrong, and it is the most interesting finding from writing the tests.
CDC's "About Adult BMI" page includes a worked table for an adult who is 5 ft 9 in tall: 124 lb or less is underweight, 125 to 168 lb is healthy weight, 169 to 202 lb is overweight, and 203 lb or more is obesity. Now compute the raw values with CDC's own formula. At 125 lb, BMI is about 18.457, which is below 18.5. At 169 lb it is about 24.954, below 25. At 203 lb it is about 29.975, below 30.
If your code compares the raw float against the thresholds, it disagrees with CDC at all three boundaries. The table only works if you round BMI to one decimal first and categorize the rounded number. That is also the only behavior that makes sense to a user: if the screen says 25.0, the label next to it should not say "healthy weight."

BMI boundary unit tests: at 5 ft 9 in, CDC's table matches only if you round to one decimal before categorizing.
And then JavaScript adds its own twist. (24.95).toFixed(1) returns "24.9" in V8, because 24.95 is stored as a binary value just under 24.95. Math.round(24.95 * 10) / 10 returns 25, because the multiplication happens to land on 249.5 exactly. The small epsilon in round1 protects the other cases where multiplication lands a hair below the half. If you need guaranteed decimal semantics, for example in a regulated product, use integer arithmetic on tenths or a decimal library and test it. For a screening display, round1 plus tests is enough.
The test suite
Node ships a test runner, so there is nothing to install. Save this next to the module and run node --test.
// metrics.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
import { bmi, bmiCategory, round1, toKg, toMeters,
waistToHeight, waistToHip } from "./metrics.mjs";
const close = (a, b, eps = 0.05) =>
assert.ok(Math.abs(a - b) < eps, `${a} !~ ${b}`);
test("CDC metric example: 68 kg, 165 cm -> 24.98", () => {
close(bmi(68, toMeters({ cm: 165 })), 24.98, 0.01);
});
test("CDC imperial example: 150 lb, 5 ft 5 in -> 24.96", () => {
close(bmi(toKg({ lb: 150 }), toMeters({ ft: 5, inches: 5 })), 24.96, 0.02);
});
test("CDC FAQ: 200 lb at 5 ft 8 in -> 30.4", () => {
assert.equal(round1(bmi(toKg({ lb: 200 }), toMeters({ ft: 5, inches: 8 }))), 30.4);
});
test("CDC 5 ft 9 in table boundaries", () => {
const h = toMeters({ ft: 5, inches: 9 });
const cat = (lb) => bmiCategory(bmi(toKg({ lb }), h));
assert.equal(cat(124), "underweight");
assert.equal(cat(125), "healthy");
assert.equal(cat(168), "healthy");
assert.equal(cat(169), "overweight");
assert.equal(cat(202), "overweight");
assert.equal(cat(203), "obesity");
});
test("round1 rounds 24.95 up, unlike toFixed", () => {
assert.equal((24.95).toFixed(1), "24.9");
assert.equal(round1(24.95), 25);
});
test("unit identity: metric and imperial agree", () => {
const metric = bmi(70, 1.75);
const imperial = bmi(toKg({ lb: 70 / 0.45359237 }),
toMeters({ inches: 175 / 2.54 }));
close(metric, imperial, 1e-9);
});
test("NICE examples: WHtR 0.57 in cm and in inches", () => {
assert.equal(waistToHeight(96.5, 170).toFixed(2), "0.57");
assert.equal(waistToHeight(38, 67).toFixed(2), "0.57");
});
test("WHR is unitless", () => {
close(waistToHip(85, 100), 0.85, 1e-12);
close(waistToHip(85 / 2.54, 100 / 2.54), 0.85, 1e-12);
});
test("rejects bad input", () => {
assert.throws(() => bmi(70, 175), RangeError); // cm passed as m
assert.throws(() => bmi(NaN, 1.75), RangeError);
assert.throws(() => bmi(70, 0), RangeError);
assert.throws(() => waistToHip(80, -1), RangeError);
});
test("BMI rises monotonically with weight at fixed height", () => {
let prev = 0;
for (let kg = 40; kg <= 150; kg += 0.5) {
const b = bmi(kg, 1.7);
assert.ok(b > prev);
prev = b;
}
});
All ten pass with node --test (I ran them on Node 24). Here is why each group exists:
-
Golden values from a third party. The CDC and NICE examples are the most valuable tests in the file, because they were not produced by your code. A test that checks
bmi(70, 1.75)against a number you computed with the same function only proves the function is deterministic. -
Boundary tests. The 5 ft 9 in table pins down both the threshold logic (
<versus<=) and the round-then-categorize order. Off-by-one-decimal bugs live here and nowhere else. -
A known JavaScript quirk, written down. The
toFixedtest documents whyround1exists. If someone later "simplifies"round1totoFixed, the boundary test fails and this test tells them why. - Identity tests. Converting the same body to imperial and back must give the same BMI. This catches the 703-versus-4.88 class of bug, a wrong conversion constant, or a toggle that converts twice.
- Invariants. Monotonicity is a cheap property test: more weight at the same height must never produce a lower BMI. It catches sign errors and accidental integer division in ports to other languages.
- Refusals. Bad input must fail loudly. A calculator that shows "BMI 0.0" for an empty field is worse than one that shows nothing.
Shipping it: labels, scope, and what the numbers do not say
Getting the arithmetic right is half the job. The other half is not letting the UI claim more than the arithmetic supports.
- State the population. CDC's adult categories are for people 20 and older; children and teens use age- and sex-specific percentiles instead. If you do not implement the pediatric method, refuse to categorize under-20 inputs rather than applying adult bands.
- Use the source's wording. "Healthy weight," "overweight," and "obesity" are CDC's labels for screening ranges. Person-first phrasing ("adults with obesity") follows CDC's own usage. Avoid red/green gauge colors that read like a pass/fail verdict.
- Show WHtR next to BMI, not instead of it. NICE recommends using waist-to-height ratio alongside BMI for adults with a BMI under 35, partly because BMI says nothing about where weight sits on the body. Two people with the same BMI can have very different waists, and a waist ratio is the cheapest way to show that.
- Tell people how to measure. NICE's method is a tape midway between the bottom of the ribs and the top of the hips, after breathing out naturally. One Reddit commenter put the practical version well: measure your actual waist with a tape, because the size printed on your trousers is not the same number. A ratio computed from a guessed waist is precise-looking noise.
- Keep it local if you can. All three metrics are pure functions of numbers the user already typed. There is no reason to send them to a server to compute them.
If you want to see these metrics in a finished product, Body Visualizer's BMI visualizer computes BMI in the browser and puts it next to a 3D outline, which is a nice illustration of the gap between a single number and a shape. Its waist-to-hip ratio calculator shows the WHO cut-offs as published context rather than as a verdict. And the main 3D body visualizer is a good reminder of the boundary I keep coming back to: BMI, WHtR and WHR are exact arithmetic on what you entered, while any silhouette drawn from them is an estimate, and should be labeled that way.
Recap
- Convert to kilograms and meters once, with exact constants, and use one BMI formula.
- Keep ratios in the same unit; they are unitless, so test that.
- Compute at full precision, round once for display, and categorize the rounded value. CDC's own 5 ft 9 in table requires it.
- Do not trust
toFixedfor half-way cases; test the boundaries. - Use third-party golden values, identity tests, invariants, and refusals.
- Label results as adult screening context, not a diagnosis.
The formulas are trivial. The test suite is what makes the feature trustworthy.
Sources
- CDC, About Adult BMI (formulas, worked examples, 5 ft 9 in table): https://www.cdc.gov/healthyweight/assessing/bmi/adult_bmi/
- CDC, BMI Frequently Asked Questions (5 ft 8 in, 200 lb example): https://www.cdc.gov/bmi/faq/index.html
- NICE NG246, Identifying and assessing overweight, obesity and central adiposity (WHtR method, examples, classifications): https://www.nice.org.uk/guidance/ng246/chapter/identifying-and-assessing-overweight-obesity-and-central-adiposity/
- WHO, Waist Circumference and WaistβHip Ratio: Report of a WHO Expert Consultation (Table A1 cut-offs): https://iris.who.int/server/api/core/bitstreams/ca408ade-05c9-4b7c-8967-6ee5b5e0ccd8/content
- r/learnprogramming, BMI formula with height in feet: https://www.reddit.com/r/learnprogramming/comments/vu4nfs/i_dont_know_whats_wrong_with_my_bmi_formula_im/
- r/learnjavascript, JS rounding problem: https://www.reddit.com/r/learnjavascript/comments/fux4ei/js_rounding_problem/
- r/javahelp, health calculator using a lb/ftΒ² constant: https://www.reddit.com/r/javahelp/comments/7yb8of/issues_with_a_calulation/
- r/mounjarouk, waist-to-height ratio discussion: https://www.reddit.com/r/mounjarouk/comments/1o9tp8i/waist_to_height_ratio/
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.