How Is Weight Trend Actually Calculated? Build a Weight Trend Line in JavaScript (EMA, Missing Days, Lag)
"Is it the average of the last 10 days? 3 weeks? I have looked and can't find an answer for this." That is the whole post. Someone on r/MacroFactor asked "Does anyone know how weight trend is actually calculated?", and
"Is it the average of the last 10 days? 3 weeks? I have looked and can't find an answer for this."
That is the whole post. Someone on r/MacroFactor asked "Does anyone know how weight trend is actually calculated?", and the top answer was honest: the app doesn't publish its exact algorithm, but "the general idea is called a moving average." Seven years earlier, a person on r/keto asked the sharper version of the same question about Happy Scale: they had logged 216.2 three days in a row, yet the app's moving average read 216.6, 216.0 and 215.6. "I've never recorded anything lower than 216.2, so I'm having trouble understanding how/why my 'moving average' is lower than that number."
If you build a weight tracker, or any chart of a noisy daily number, you will get both questions, and both deserve an answer you can explain in one sentence.
This post builds a small, dependency-free JavaScript module for a weight trend line: a simple moving average, the exponential moving average popularized by The Hacker's Diet, and double exponential (Holt) smoothing. It also handles missing days, units, time zones and rounding. Everything is covered by a node --test suite, and every number in the charts below is checked by those tests.
Who asks, and what they actually want
The question shows up in three places, phrased three ways:
- App users (r/MacroFactor, r/loseit, r/keto, the MyFitnessPal forums) want to know what the trend number means. Is it a 10-day average? Why did it go up when today's weigh-in went down? A MyFitnessPal forum user asked how Libra calculates its trend because their own "mathematical average" was half a pound different.
- Spreadsheet people (r/spreadsheets) want a formula. One asker had a 10-day simple moving average in Apple Numbers and wanted "the 10 day weighted moving average, with exponential smoothing," after reading The Hacker's Diet. "For the life of me I cannot get it right."
- Developers want the version that survives real data: irregular weigh-ins, two entries on one day, a two-week holiday. A classic Stack Overflow question, "Exponential Moving Average Sampled at Varying Times," asks exactly how to vary alpha when samples don't arrive on schedule.
They all want a trend line that ignores day-to-day noise, explains itself, and doesn't invent data.
Three ways to calculate a weight trend

How is weight trend calculated? The same synthetic weigh-ins smoothed three ways. The EMA lags while the weight is changing; Holt removes the lag but overshoots after the plateau.
The chart uses synthetic data: a line that drops 0.07 kg per day for 45 days and then goes flat, plus random noise, rounded to 0.1 kg like a bathroom scale. Because I generated it, we know the "true" line.
1. Simple moving average (SMA). Average the weigh-ins from the last N days. It's easy to explain and easy to do in a spreadsheet. The catch is that every day in the window counts equally, so a single unusual weigh-in moves a 7-day average twice: once when it arrives, and again seven days later when it drops out.
2. Exponential moving average (EMA). Every day, move the trend a fixed fraction of the way toward today's weight:
trend = trend + alpha * (weight - trend)
This is the formula The Hacker's Diet gives, with alpha = 0.1: "subtract yesterday's trend from today's weight", shift the decimal one place left, and add the result to yesterday's trend. Expand the recurrence and today's weigh-in carries 10% of the weight, yesterday's 9%, the day before 8.1%, and so on, fading geometrically and never quite reaching zero. It needs only one number of state, it has no window edge, and it is a weighted average of real weigh-ins, so it can never go below your lowest entry or above your highest.
3. Double exponential smoothing (Holt). Keep two numbers: a level and a slope. Each day, predict today as level + slope, blend that prediction with the real weigh-in, then update the slope from how much the level moved. The NIST Engineering Statistics Handbook gives the two equations; the slope term exists to cancel lag when the data has a trend.
Happy Scale's support page describes four smoothing methods, two "simple" (exponential smoothing and a seven-day moving average) and two "advanced" (its own method and double exponential smoothing). It says plainly that the advanced methods compensate for lag by tracking your current trend, and that after a plateau they "temporarily predict that you will continue to trend downward. This sometimes causes them to predict weights you've never achieved."
That is the r/keto mystery solved. A double exponential trend extrapolates. In the chart, the Holt line dips to 78.52 kg on day 57, below every weigh-in that week (the lowest was 78.7 kg) and 0.33 kg under the flat line the data was generated from. Nothing is broken. The method is built to do this.
The lag you are trading for smoothness
The EMA has the opposite problem. While weight is moving steadily, the EMA trails behind it, and the gap has a closed form. For a series changing by s per day, a smoothed value with constant alpha settles at:
lag = s * (1 - alpha) / alpha
With alpha = 0.1 that's nine days' worth of change. If a series falls 0.1 kg per day, the EMA sits 0.9 kg above the latest weight, which is why the trend line "rides above" the dots during a steady loss. In the synthetic chart the slope is 0.07 kg/day, so theory says about 0.63 kg. On day 44, with noise included, the EMA happens to sit 0.78 kg above the underlying line.
Robert Nau's forecasting notes at Duke put this in terms of the "average age" of the data: (m + 1) / 2 periods for an m-term simple moving average, and 1/alpha for simple exponential smoothing. Set them equal and alpha = 0.1 has the same average age as a 19-day simple average. It's a useful sentence for your settings screen: "Smoothing 0.1 is about as slow as a 19-day average."
So the honest product framing is this. The EMA tells you roughly where you were about a week and a half ago, very smoothly. Holt tells you where you probably are today, but it can overshoot when the direction changes. Pick one, label it, and say which in the UI. A forum user described Libra's trend as alpha = 1 / smoothing days, which is a reasonable way to expose the knob even if you never show the word "alpha".
The module
Here is the core of weightTrend.mjs, a single dependency-free ES module of about 160 lines. Small helpers such as isoFromDayNumber and the MIN_KG/MAX_KG constants are omitted for space.
Step 1: one unit, one value per calendar day
export const KG_PER_LB = 0.45359237; // exact by definition
export const lbToKg = (lb) => lb * KG_PER_LB;
export const kgToLb = (kg) => kg / KG_PER_LB;
const DAY_MS = 86_400_000;
export function dayNumber(isoDate) {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(isoDate);
if (!m) throw new RangeError(`Expected YYYY-MM-DD, got "${isoDate}"`);
return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])) / DAY_MS;
}
export function localDateKey(instant, timeZone) {
return new Intl.DateTimeFormat("en-CA", {
timeZone, year: "numeric", month: "2-digit", day: "2-digit",
}).format(instant); // "YYYY-MM-DD"
}
Three decisions hide in these few lines:
- Store kilograms unrounded. The international pound is defined as exactly 0.45359237 kg, so converting is lossless if you keep full precision. Round only in the formatter. The tests walk every 0.1 lb from 90 to 400 through kg and back.
-
A weigh-in belongs to the user's calendar day, not the server's. A 10:30 PM weigh-in in New York is already "tomorrow" in UTC. Group by
localDateKey(instant, userTimeZone), and store the zone with the user. -
Count days with UTC date math. If you subtract two local-midnight timestamps across a daylight-saving change, you get 23 or 25 hours.
Date.UTCon the date string avoids that, and the tests check both US transitions.
Then collapse each day to one value. Two weigh-ins on the same morning shouldn't count as two days of evidence:
export function dailyMeans(entries) {
const byDay = new Map();
const rejected = [];
for (const e of entries) {
const kg = Number(e.kg);
let day;
try { day = dayNumber(e.date); } catch { rejected.push(e); continue; }
if (!Number.isFinite(kg) || kg < MIN_KG || kg > MAX_KG) { rejected.push(e); continue; }
const acc = byDay.get(day) ?? { sum: 0, n: 0 };
acc.sum += kg; acc.n += 1;
byDay.set(day, acc);
}
const points = [...byDay.entries()]
.sort((a, b) => a[0] - b[0])
.map(([day, { sum, n }]) => ({ day, date: isoFromDayNumber(day), kg: sum / n, n }));
return { points, rejected };
}
The 20-400 kg range is a product policy for catching typos like 8040, not a statement about people. Return the rejects so the UI can ask instead of silently dropping them.
Step 2: the smoothers
export function ema(points, { alpha = 0.1, gaps = "decay" } = {}) {
const series = gaps === "interpolate" ? interpolateDaily(points) : points;
const out = [];
let trend, prevDay;
for (const p of series) {
if (trend === undefined) {
trend = p.kg; // day one: trend = first weight
} else {
const days = p.day - prevDay;
const a = gaps === "decay" ? 1 - (1 - alpha) ** days : alpha;
trend += a * (p.kg - trend);
}
prevDay = p.day;
out.push({ day: p.day, date: p.date, value: trend, interpolated: Boolean(p.interpolated) });
}
return out;
}
export function holt(points, { alpha = 0.1, beta = 0.1 } = {}) {
const out = [];
let level, slope = 0;
for (const p of points) {
if (level === undefined) {
level = p.kg;
} else {
const prevLevel = level;
level = alpha * p.kg + (1 - alpha) * (prevLevel + slope);
slope = beta * (level - prevLevel) + (1 - beta) * slope;
}
out.push({ day: p.day, date: p.date, value: level, slopePerDay: slope });
}
return out;
}
I start Holt's slope at zero. NIST lists several ways to initialize it, such as the first difference or the average of the first few, but with noisy weigh-ins the first difference is mostly noise. Starting at zero means the line needs a couple of weeks to "learn" a direction, which is a better failure mode than shooting off on day two.
The SMA in the module averages over the last N calendar days, not the last N entries. If someone weighs in on days 0, 10 and 11, the 7-day average on day 11 shouldn't include day 0.
Missing days: pick a rule and say so

How is weight trend calculated when you skip days? Three honest rules for a 10-day gap give three different trend values on day 40. On the right, rounding each daily step freezes the trend.
People don't weigh in every day. The gaps option chooses what a gap means:
-
"skip"treats each entry as one step, however many days passed. That's the pencil-and-paper reading of The Hacker's Diet. After a ten-day holiday, the first weigh-in still moves the trend only 10%. In the synthetic example, where post-gap readings sit about 1.4 kg higher, the trend on day 40 is 80.73 kg. -
"decay"usesa = 1 - (1 - alpha) ** days. For an 11-day jump that's 1 - 0.9^11, about 0.69, so the new reading counts much more (81.17 kg on day 40). It's exactly what you'd get by feeding today's weight once for every elapsed day; there's a test for that equivalence. It's the discrete cousin of the1 - e^(-dt/tau)answer accepted on the Stack Overflow question. -
"interpolate"fills the gap with a straight line between the weigh-ins on either side, then smooths day by day (80.87 kg on day 40). This is what TrendWeight's documentation describes for days you don't weigh in. One side effect to be aware of: the filled days only exist once the next real weigh-in arrives, so the trend line for past days can change after the fact.
None of these is "correct." The data doesn't say what happened during the gap. What you owe your users is consistency and a visible marker: draw interpolated days differently, and don't connect the line through a gap you didn't fill. A 2015 r/loseit poster built their own Chrome extension partly because MyFitnessPal's chart "inserts fake data points when ever you miss a day." The module's toSvgPath starts a new subpath (M) whenever two points are more than maxGapDays apart:
export function toSvgPath(series, { x, y, maxGapDays = 3, decimals = 1 } = {}) {
let d = "";
let prevDay;
for (const p of series) {
const cmd = prevDay === undefined || p.day - prevDay > maxGapDays ? "M" : "L";
d += `${d ? " " : ""}${cmd}${x(p.day).toFixed(decimals)},${y(p.value).toFixed(decimals)}`;
prevDay = p.day;
}
return d;
}
Unlike a height chart, a weight-over-time chart doesn't need a y-axis that starts at zero. The question it answers is "how is this changing," not "how big is this." Just label the axis and keep the scale fixed while the user scrolls through time.
Rounding belongs at the display edge
The right-hand panel shows a small trap in the pencil method. The Hacker's Diet tells you to round each day's step to one decimal place, which is sensible on paper. In code it means that once the gap between weight and trend is under about half a unit, 0.1 * diff rounds to zero every day. With a trend at 80.0 and weigh-ins of 79.6 forever, the rounded trend stays at 80.0 indefinitely, while the full-precision EMA converges toward 79.6.
The fix is the same one that applies to unit conversions: keep full precision in state and round in formatWeight() and nowhere else. The test suite includes the r/Fitness worked example (200, 202, 204, 210, 204 lb gives trends of 200, 200.2, 200.58, 201.52, 201.77) at full precision. It also pins the pencil version (200.6, 201.5, 201.8) so nobody "simplifies" storage back to one decimal later.
Tests worth keeping
The test file has 12 tests and runs on plain Node with no dependencies:
test("EMA never leaves the range of the weigh-ins; Holt can (the 'lower than any entry' question)", () => {
const down = Array.from({ length: 30 }, (_, i) => 220 - 0.13 * i);
const flat = Array(6).fill(216.2);
const pts = series([...down, ...flat]);
const e = ema(pts, { alpha: 0.1, gaps: "skip" });
const h = holt(pts, { alpha: 0.1, beta: 0.1 });
const minWeight = Math.min(...pts.map((p) => p.kg));
assert.ok(e.every((p) => p.value >= minWeight - 1e-12));
assert.ok(h.at(-1).value < 216.2);
});
test("EMA lags a steady trend by slope * (1 - alpha) / alpha", () => {
const pts = series(Array.from({ length: 300 }, (_, i) => 90 - 0.1 * i));
const last = ema(pts, { alpha: 0.1, gaps: "skip" }).at(-1);
close(last.value - pts.at(-1).kg, 0.9, 1e-6);
});
test("gaps: 'decay' equals feeding the new weight once per elapsed day", () => {
const withGap = [{ day: 0, kg: 80 }, { day: 4, kg: 82 }];
const daily = series([80, 82, 82, 82, 82]);
close(ema(withGap, { gaps: "decay" }).at(-1).value, ema(daily, { gaps: "skip" }).at(-1).value);
});
The rest cover exact lb/kg round trips, DST-safe day counting, local-date grouping in two time zones, same-day averaging and typo rejection, the calendar-day SMA window, weeklyChange returning null instead of a made-up number when there is no value seven days back, and the SVG gap breaks. One test reads a JSON fixture written by the script that draws the charts and checks that the JavaScript produces the same 78.52, 80.73, 81.17 and 80.87 printed in this article. If the charts and the code ever disagree, CI fails.
Showing the trend to people
A few product notes that matter as much as the math:
- Lead with the trend, keep the dots. Show the smoothed number large, with today's weigh-in visible but quieter.
- Explain the method in one line, next to the number. For example: "Trend: exponential moving average, about as slow as a 19-day average." If you use Holt, add: "can keep moving for a few days after a plateau."
- Use the trend as the input for anything derived. If your app recalculates a plan or a BMI from "current weight," feed it the trend, not one morning's reading. Body Visualizer's weight loss calculator suggests recalculating with your actual weight every 2-4 weeks. A trend value is a steadier thing to type into it than a single weigh-in, and the BMI visualizer works the same way: the ratio is only as stable as the weight you give it.
- Don't decorate noise. Avoid streaks, red/green verdicts, or celebratory animations on a single day's change.
If you want to show what a trend range looks like rather than a number, a slider that moves weight at a fixed height, like Body Visualizer's weight simulator, is a reasonable pattern. It's an estimated 3D silhouette, not a body scan, and it should be labeled that way. Nothing in this post is health advice; it's signal processing applied carefully to a noisy number.
Checklist
- [ ] One canonical unit (kg), stored unrounded; round only in formatters.
- [ ] Weigh-ins grouped by the user's local calendar date; days counted with UTC date math.
- [ ] Multiple same-day entries averaged; out-of-range entries returned for confirmation, not silently dropped.
- [ ] A named smoothing method with its lag or overshoot explained in the UI.
- [ ] An explicit gap rule (
skip,decay, orinterpolate), with interpolated days drawn differently. - [ ] No line drawn through unfilled gaps; no weekly rate without data seven days back.
- [ ] Tests that pin your published examples to the code.
Wrapping up
So, how is weight trend calculated? Usually as an exponential moving average: move 10% of the way from yesterday's trend toward today's weight, every day. Some apps add a slope term (double exponential smoothing) to remove lag, and that's why a trend can sit below every number you've logged. The formula takes one line. The real work is in the decisions around it: units, calendar days, gaps, rounding, and telling people which method they are looking at.
Sources
- r/MacroFactor, "Does anyone know how weight trend is actually calculated?" (June 2024): https://www.reddit.com/r/MacroFactor/comments/1da2g3c/does_anyone_know_how_weight_trend_is_actually/
- r/keto, "Happy scale question - moving average weight" (July 2017): https://www.reddit.com/r/keto/comments/6m78gl/happy_scale_question_moving_average_weight/
- r/spreadsheets, "Average Weight" (December 2020): https://www.reddit.com/r/spreadsheets/comments/kn086b/average_weight/
- r/Fitness, "Daily/weekly weight fluctuations: How do you figure out your actual weight?" (worked 10% trend example): https://www.reddit.com/r/Fitness/comments/2hhbqa/dailyweekly_weight_fluctuations_how_do_you_figure/
- r/loseit, "I hate MyFitnessPal's graphs, so I made my own" (2015): https://www.reddit.com/r/loseit/comments/3jonsl/i_hate_myfitnesspals_graphs_so_i_made_my_own/
- MyFitnessPal Community, "Libra question": https://community.myfitnesspal.com/en/discussion/10599995/libra-question
- Stack Overflow, "Exponential Moving Average Sampled at Varying Times": https://stackoverflow.com/questions/1023860/exponential-moving-average-sampled-at-varying-times
- John Walker, The Hacker's Diet, "Food and Feedback" (trend calculation): https://www.fourmilab.ch/hackdiet/e4/pencilpaper.html
- Happy Scale Support (smoothing methods): https://happyscale.com/support.en
- NIST/SEMATECH e-Handbook of Statistical Methods, 6.4.3.3 Double Exponential Smoothing: https://itl.nist.gov/div898/handbook/pmc/section4/pmc433.htm
- Robert Nau, Duke University, "Averaging and exponential smoothing models": https://people.duke.edu/~rnau/411avg.htm
- TrendWeight, "The math of TrendWeight" (interpolation): https://raw.githubusercontent.com/ervwalter/trendweight/main/apps/web/src/components/math/math-of-trendweight.md
- NIST Handbook 44 (2024), Appendix B (pound = 0.45359237 kg exactly): https://www.nist.gov/system/files/documents/2024/01/14/NIST%20HB%2044%202024%20Appendix%20B%20Units%20and%20Systems%20of%20Measurement.pdf
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.