"Why is my BMI calculator showing the wrong BMI?"
That's the title of a Stack Overflow question from April 2020. The asker wrote: "It was working fine until yesterday, but then it stopped showing the correct BMI. I am pretty sure all of my document.getElementById's are correct." Two years later, on r/learnjavascript, a student with a course assignment posted "Beginner JS user doesn't understand why his code isn't working". The code calculated NaN while the page was loading, before anyone had clicked anything, and it had a typo in the constant as well. Later that year another Stack Overflow asker wrote that hitting Calculate on an empty form "renders the NAN as a 'result'. And if I just input the weight, it returns an Infinity response."
The project hasn't gone anywhere. On X, between September and December 2026, I counted more than a dozen posts from people learning JavaScript or Python who had just built a BMI calculator, many of them as part of #100DaysOfCode. One wrote, "The tricky part? Switching between Metric and Imperial units using CSS." Another, on 2 December, was on "Day 9/53" and had just learned to read input with .value.
The formula really is one line. CDC gives it as weight (kg) / [height (m)]^2, or weight (lb) / [height (in)]^2 x 703 in U.S. units. The bugs are in the other forty lines: reading the inputs, converting units, the timing of the event handler, and the if chain that picks a category. Each bug leaves its own fingerprint, a characteristic wrong number. So this post takes a different route from the usual "here's my working calculator": it reproduces the common bugs in a small JavaScript module, shows what each one prints for the same person, and gives you a diagnose() function that goes from the number on your screen back to the likely cause. Everything is pinned down with 17 node --test tests.
Scope note: BMI is an adult screening number, and this is arithmetic, not medical advice. The category labels below are CDC's adult categories. Children and teens use BMI-for-age percentiles, which this code doesn't do.
Step 0: get a number you trust
You can't debug "wrong" without a "right". Before touching the code, collect a few golden values from someone else's arithmetic:
- CDC's FAQ: an adult who is 5 ft 8 in and 200 lb has a BMI of 30.4.
- CDC's adult categories page has a table for a 5 ft 9 in adult: 124 lb or less is underweight, 125 to 168 lb healthy weight, 169 to 202 lb overweight, and 203 lb and up in the obesity range (with class boundaries at 237 and 271 lb).
- Body Visualizer's BMI visualizer uses two adults at 175 cm and 76.6 kg, both BMI 25.0, as its example of why one BMI can come with very different waists. That makes it a handy metric test case, and you can type your own inputs into the page to compare its output with yours.
Golden values matter because a lot of BMI bugs produce numbers that look fine. I'll use one person throughout: 5 ft 9 in, 160 lb. The correct BMI is 703 x 160 / 69^2 = 23.6.
The fingerprint table
Here's what fourteen implementations print for that same person. Thirteen of them are bugs, either taken from real questions or reproduced from common mistakes.

Why is my BMI calculator showing the wrong BMI? Each bug prints a characteristic number. The amber ones are the dangerous ones: wrong, but believable.
The rose bars are easy. Nobody ships a calculator that says 0.00236 without noticing. The amber bars are the problem: 24.53, 30.56, 31.24 and 22.44 are all BMIs a real adult could have, so they get through a quick manual check. For 30.56 and 31.24 the category label changes as well.
Because each bug produces a different number, you can run the table backwards:
import { person, diagnose } from "./bmi.mjs"; const me = person(5, 9, 160); // ft, in, lb diagnose(me, "30.56"); // -> [{ id: "sumOfSquares", label: "squares feet and inches separately: (ft x 12)^2 + in^2", value: 30.556... }] diagnose(me, "0.30"); // -> stringConcat diagnose(me, NaN); // -> readBeforeClick diagnose(me, "41.7"); // -> [] not a known fingerprint, go read the code diagnose() runs every reproduced bug on the same inputs and returns the ones whose output matches what you printed. It matches at the precision you printed, so "23.6" covers 23.55 to 23.65. It isn't magic. Two bugs could collide for some unlucky input, and a bug that isn't in the table returns nothing. But for the classic project, typing your inputs and your wrong answer usually narrows it to one line of code. Now let's go through the bugs.
Bug 1: squaring feet and inches separately (30.56)
This is the bug from the 2020 question that gave this post its title. Simplified, the code was:
var ftInches = ft * 12; var ftInchesSq = ftInches * ftInches; var inchesSq = inches * inches; var heightSquared = inchesSq + ftInchesSq; // (ft*12)^2 + in^2 var bmi = (pounds / heightSquared * 703).toFixed(2); Height squared is (60 + 9)^2 = 4,761. This code computes 60^2 + 9^2 = 3,681. The square of a sum isn't the sum of the squares, because it's missing the 2ab term. At 5 ft 9 in the denominator shrinks by about 23%, so the BMI comes out about 29% too high (more at 5 ft 11 in, less at 5 ft 1 in). At 160 lb that's 30.56 instead of 23.63, and the label jumps from "Normal weight" to "Obesity class 1".
It also explains "it was working fine until yesterday". For anyone whose height is a whole number of feet, the inches term is zero and the bug disappears: at 6 ft 0 in the code is exactly right. It starts lying once you test a different height.
The only answer on that question that wasn't voted below zero blamed the && syntax in the category checks. That was a red herring: b > 18.51 && b < 24.99 parses fine in JavaScript, because comparison binds tighter than &&. It's a good reminder that when a number is wrong, you should check the number before the branching.
Fix: add first, convert once, square last.
export function toMeters(h) { if ("m" in h) return num(h.m, "m"); if ("cm" in h) return num(h.cm, "cm") / 100; if ("ft" in h || "in" in h) { const ft = num(h.ft ?? 0, "ft"); const inch = num(h.in ?? 0, "in"); return (ft * 12 + inch) * M_PER_IN; // add first, THEN convert (and square later) } throw new TypeError("height needs m, cm, or ft/in"); } num() throws if it gets anything but a finite number. That matters for the next bug.
Bug 2: strings that look like numbers (0.30, and friends)
input.value is always a string. JavaScript's *, / and ** quietly convert strings to numbers, which is why a lot of beginner code works by accident. + doesn't. If either side is a string, it concatenates:
5 * 12 + "9" // "609" ("609") ** 2 // 370881, because ** converts it back 703 * 160 / 370881 // 0.3033 So a height that should be 69 inches becomes 609 inches, and the BMI comes out around 0.3. It's obviously wrong, but confusing if you've only ever seen * "just work".
The usual fix is parseFloat, but it's more forgiving than you want. parseFloat("70kg") is 70, and parseFloat("5'11") is 5, so someone who types their height the way they'd say it gets the height of a five-foot person with no error. The module uses a strict parser instead:
export function parseField(raw, { allowComma = true } = {}) { if (raw == null) return { ok: false, reason: "missing" }; let s = String(raw).trim(); if (s === "") return { ok: false, reason: "empty" }; if (allowComma && /^\d+,\d+$/.test(s)) s = s.replace(",", "."); // "1,70" -> "1.70" if (!/^[+-]?(\d+\.?\d*|\.\d+)$/.test(s)) return { ok: false, reason: "not-a-number" }; const value = Number(s); if (!Number.isFinite(value)) return { ok: false, reason: "not-a-number" }; if (value <= 0) return { ok: false, reason: "not-positive" }; return { ok: true, value }; } It returns a reason instead of a number, so the UI can say "that isn't a number" rather than printing one.
<input type="number"> doesn't make this go away. The 2022 question used type="number" with the placeholder "Ex: 1,70", which is a comma decimal, natural for its Portuguese-speaking audience. Whether a browser accepts a comma in a number field depends on the browser and locale. When it can't parse what was typed, the HTML spec's value sanitization sets .value to the empty string. That means "" can mean "the user typed nothing" or "the user typed something the browser rejected", and your code can't tell which. validity.badInput can:
export function readNumberInput(el) { if (el?.validity?.badInput) return { ok: false, reason: "bad-input" }; return parseField(el?.value); } One more type="number" detail: the default step is 1, so if you use a real <form> submit, a height of 1.70 m fails constraint validation until you add step="any" (or step="0.01").
Bug 3: reading the inputs at the wrong time (NaN)
The 2022 r/learnjavascript code ended with this line:
document.getElementById("calcBMI").addEventListener("click", doCalcBMI()) The parentheses call doCalcBMI right away, while the page is loading and both fields are empty, and then pass its return value (undefined) to addEventListener. The page shows NaN on load, and the button does nothing afterwards. The top reply gave both fixes: convert with Number(), and pass doCalcBMI without the parentheses. A 2018 Stack Overflow question had the same bug in a different form: the values were read into variables at the top of the script, outside the click handler, so they were empty forever.
The test reproduces it with a fake button, with no DOM library needed:
const listeners = []; const button = { addEventListener: (type, fn) => listeners.push(fn) }; button.addEventListener("click", calc()); // the bug: calc runs now, registers undefined assert.ok(Number.isNaN(out[0])); assert.equal(listeners[0], undefined); Empty fields have fingerprints of their own. "" / ("" * "") is 0 / 0, which is NaN. A weight with no height is 70 / 0, which is Infinity, the exact symptom in the 2022 question. A height with no weight is 0, and since 0 is less than 18.5, a naive chain happily labels it "Underweight". So a "0.0 Underweight" on screen usually means an empty field, not a calculation. An r/learnprogramming question from 2023 showed one more variation: bmiCalculator() was called with no arguments, so both parameters were undefined and the result was NaN.
Fix: read inside the handler, parse strictly, and don't compute until both fields are valid. "Show nothing yet" is a valid state, and it's better than NaN.
Bug 4: right formula, wrong units (22.44, 31.24, 52.09, 72.57)
Unit switching was "the tricky part" for that X poster, and this is where the amber bars come from. Each of these gives a plausible number:
- Decimal feet. Someone types 5'9" as
5.9, and the code treats it as 5.9 feet, which is 70.8 inches. The result is 22.44 instead of 23.63. It gets stranger: 5'10" typed as5.10is 5.1 feet (61.2 in) and gives 30.03. The taller person gets the higher BMI, from a shorter height. -
parseInton a decimal.parseInt("5.9")is 5, so the height becomes 60 inches and the BMI 31.24. In metric it's worse:parseInt("1.75")is 1, so the BMI equals the weight in kilograms (72.57 here). If your BMI always matches the weight, that's the bug. - A typo in the constant. The 2022 r/learnjavascript code multiplied by
730, not703. That makes every result 3.8% too high: 24.53 instead of 23.63. It's close enough to pass a glance, which is exactly why you want a golden-value test. - Pounds in the metric formula gives 52.09. Kilograms in the 703 formula gives 10.72.
- Centimetres where metres are expected gives 0.00236. CDC also publishes a centimetre form,
kg / cm / cm x 10,000. Lose the 10,000 and you get exactly this number.
The cure is a single canonical unit plus validation that knows what the common mistakes look like. computeBmi() converts everything to kilograms and metres, refuses anything outside an adult range, and tries to say why:
computeBmi({ height: { m: 175 }, weight: { kg: 70 } }); // { ok: false, reason: "height-out-of-range", hint: "That looks like centimetres in a metres field." } computeBmi({ height: { ft: 5, in: 13 }, weight: { lb: 160 } }); // { ok: false, reason: "inches-out-of-range", hint: "Inches should be 0 to 11; put whole feet in the feet field." } computeBmi({ height: { ft: 5, in: 9 }, weight: { lb: 160 } }); // { ok: true, value: 23.627..., display: "23.6", category: "Healthy Weight" } Separate feet and inches fields stop the decimal-feet bug before it starts. If you'd rather have one field, do what Body Visualizer's reverse BMI calculator does and label it as total inches ("5 ft 10 in = 70 in"). That page also says it accepts decimals "with a point or comma", which is the allowComma behaviour above.
Bug 5: the number is right but the category is missing
Sometimes the BMI is correct and the label is wrong, or there's no label at all. Both Stack Overflow questions copied their category logic from a table that reads "18.5-24.9, 25-29.9, ..." and turned each row into a pair of strict comparisons:
// SO 61160326 (on bmi.toFixed(2), a string) if (bmi > 18.51 && bmi < 24.99) ... if (bmi > 25 && bmi < 29.99) ... // SO 74004685 (on the raw float) else if (BMI > 18.5 && BMI < 24.9) ... else if (BMI > 25 && BMI < 29.9) ... else window.alert("please add the information") Every value between 24.9 and 25, and every value equal to a boundary, makes all the branches false. In the first version the output box keeps whatever it showed last. In the second, a person with a perfectly valid BMI of 24.95 is asked to fill in the form.

Why is my BMI calculator showing the wrong BMI? Sometimes it's the right number with no category. Rose shows where every branch of a copied if-chain is false.
I walked 5 ft 9 in from 80 to 320 lb in 0.1 lb steps, 2,401 weights. The first chain leaves 6 of them unlabelled and the second leaves 27. That's rare enough to survive casual testing and common enough that some real user will hit it.
CDC's own wording avoids the problem: "18.5 to less than 25", "25 to less than 30". Those are half-open intervals. Write them as one ordered list, check < in order, and there can't be a gap:
export const CATEGORIES = [ { below: 18.5, label: "Underweight" }, { below: 25, label: "Healthy Weight" }, { below: 30, label: "Overweight" }, { below: 35, label: "Class 1 Obesity" }, { below: 40, label: "Class 2 Obesity" }, { below: Infinity, label: "Class 3 Obesity" }, ]; export const round1 = (x) => Math.round(x * 10 + 1e-9) / 10; export function bmiCategory(b) { const shown = round1(b); return CATEGORIES.find((c) => shown < c.below).label; // never undefined: last band is open } The category is chosen from the rounded value you display, so the screen never shows "25.0, Healthy Weight". That's also the only way CDC's 5 ft 9 in table comes out right at 125, 169 and 203 lb. I went through that rounding trap (and why (24.95).toFixed(1) gives "24.9") in an earlier post on BMI, WHtR and WHR in JavaScript, so I won't repeat it here. One related detail: toFixed() returns a string. Comparing that string with a number works, because JavaScript converts it, but bmi + 1 won't do what you expect. Keep the number as a number and format it only at the end.
Wiring it to the page
With parsing, units and categories in a module, the DOM code is short and has almost nothing left to get wrong:
import { readNumberInput, computeBmi } from "./bmi.mjs"; const form = document.querySelector("#bmi"); const out = document.querySelector("#result"); // <output aria-live="polite"> function render() { const h = readNumberInput(form.height); // read NOW, inside the handler const w = readNumberInput(form.weight); if (!h.ok || !w.ok) { // empty or unparseable: say so, don't compute out.textContent = h.reason === "bad-input" || w.reason === "bad-input" ? "Please enter numbers only." : ""; return; } const r = computeBmi({ height: { cm: h.value }, weight: { kg: w.value } }); out.textContent = r.ok ? `BMI ${r.display} (${r.category}, adult screening category)` : r.hint; } form.addEventListener("input", render); // no parentheses render is passed, not called. Values are read inside the handler. Empty or rejected fields produce a message, not a number. Everything else lives in plain functions you can test without a browser.
The tests
The suite has 17 tests and runs with node --test in under 100 ms. They fall into four groups:
- Golden values from other people's arithmetic. CDC's 5 ft 8 in / 200 lb = 30.4, every row boundary of CDC's 5 ft 9 in table (124/125, 168/169, 202/203, 236/237, 270/271 lb), and 175 cm / 76.6 kg = 25.0 from the BMI visualizer page. If the formula or the rounding order is wrong, these fail first.
- One test per bug. Each test reproduces a bug and asserts its fingerprint (30.56, "609", 730 vs 703, 22.44 vs 30.03, NaN / Infinity / 0, the
addEventListener(calc())trap), next to the fixed behaviour. If someone later "simplifies" the code back into the bug, a test with a descriptive name fails. - Properties. The
703shortcut agrees with exactkg / m^2within 0.01 BMI across an adult grid. The half-open categories label every one of the 2,401 weights, and the category never goes down as weight goes up. - Charts can't drift. Both figures in this post are drawn from
fixtures/figures.json, which the module writes and the last test checks against the module.
When you add your own boundary tests, a reverse BMI tool is a convenient oracle. Weight = BMI x height^2, so you can generate the weight that sits exactly on 25.0 for any height and check that your forward function agrees. That's also how you catch an inverted unit conversion, because the round trip won't close.
$ node --test ok golden: CDC FAQ, 5 ft 8 in and 200 lb is BMI 30.4 ok golden: CDC 5 ft 9 in table, every row boundary lands in the right category ok SO 61160326: squaring feet and inches separately turns 23.6 into 30.6 ok diagnose: each printed number points back to the bug that produced it ok category gaps: copied if-chains leave weights unlabeled; half-open intervals never do ... tests 17 | pass 17 | fail 0 A checklist for "why is my BMI calculator showing the wrong BMI?"
Run through these in order. Each step rules out one row of the fingerprint table.
- [ ] Compare against a golden value (CDC's 5 ft 8 in / 200 lb = 30.4) before you trust any output.
- [ ] Is the number too high for everyone except people who are a whole number of feet tall (about 29% at 5 ft 9 in)? You're squaring feet and inches separately.
- [ ] Is it a steady 3.8% too high? Check the constant: 703, not 730.
- [ ] Is it near 0.3, or does the code use
+on.value? That's string concatenation. Convert before you add. - [ ]
NaNon page load? Check foraddEventListener("click", fn())or values read outside the handler. - [ ]
Infinitymeans the height is empty or zero.0(and "Underweight") means the weight is empty. - [ ] Does the BMI equal the weight in kg?
parseInttruncated the height to 1 m. - [ ] Is it about 10,000 times too small? Centimetres went into a metres formula.
- [ ] A plausible number that's slightly off? Check for decimal feet ("5.9"),
parseFloat("5'11"), and lb/kg swaps. - [ ] Right number but no label, or a stale label? Replace the
&&chain with ordered half-open intervals on the rounded value. - [ ]
<input type="number">: checkvalidity.badInput, and setstep="any"if you submit a form.
So why is it showing the wrong BMI?
Rarely because of the formula itself. In the questions I looked at, kg / m^2 was only wrong once, through a mistyped constant. What broke was everything around it: a height squared in two pieces, a string where a number should be, a handler that ran before anyone typed, a unit nobody converted, or an if-chain with holes in it. Each of these prints its own characteristic number, so the fastest way to debug is to work out the right answer for one person, see what you printed instead, and look it up in the table.
The module is about 230 lines with no dependencies, and the tests run in well under a second. If you're building this as a learning project, I'd suggest writing the golden-value tests before the DOM code. Then the console tells you the answer is wrong before a user does.
Sources
- Stack Overflow 61160326, "Why is my BMI calculator showing the wrong BMI?" (Apr 2020): https://stackoverflow.com/questions/61160326
- Stack Overflow 74004685, "Why does my code return NAN and Infinity?" (Oct 2022): https://stackoverflow.com/questions/74004685
- Stack Overflow 51641585, "Javascript - Input Value NaN" (Aug 2018): https://stackoverflow.com/questions/51641585
- r/learnjavascript, "Beginner JS user doesn't understand why his code isn't working" (Jul 2022; addEventListener(fn()) and the 730 constant): https://www.reddit.com/r/learnjavascript/comments/vw6qyc/beginner_js_user_doesnt_understand_why_his_code/
- r/learnprogramming, "Two var prompts in a function returning NaN." (Jan 2023): https://www.reddit.com/r/learnprogramming/comments/10piedz/two_var_prompts_in_a_function_returning_nan/
- r/learnjavascript, "NaN value in input field" (Nov 2020): https://www.reddit.com/r/learnjavascript/comments/jplxw6/nan_value_in_input_field/
- X, "Project 7/18: BMI Calculator is live ... The tricky part? Switching between Metric and Imperial units" (Oct 2026): https://x.com/Judeirom/status/2114998033960083538
- X, "Day 9/53 Built a JavaScript BMI Calculator" (Dec 2026): https://x.com/anand04_vs/status/2128201330510660078
- CDC, BMI Frequently Asked Questions (formulas; 5 ft 8 in, 200 lb = 30.4): https://www.cdc.gov/bmi/faq/index.html
- CDC, Adult BMI Categories (half-open ranges; 5 ft 9 in table): https://www.cdc.gov/bmi/adult-calculator/bmi-categories.html ...
