DEV Community

Saurabh Sharma
Saurabh Sharma

Posted on

JavaScript told me to buy 8 bags of concrete. I needed 7.

Brute-forcing 12,600 slab math combos

Open your browser console and paste this:

4 * 3 * (4 / 12) * 1.05 / 0.6
Enter fullscreen mode Exit fullscreen mode

That's a small pad for an AC unit. 4 ft by 3 ft, 4 inches thick, plus 5% extra for spillage, divided by 0.6 cubic feet (what one 80 lb bag of concrete mix makes). On paper the answer is 7. Exactly 7 bags.

JavaScript says 7.000000000000001.

Every bag calculator rounds up, because nobody sells 0.4 of a bag. So you wrap it in Math.ceil() and the page tells you to buy 8.

One extra bag isn't a disaster. It's six bucks and 80 more pounds to drag across a parking lot. But I wanted to know how often it happens, so I brute-forced it.

How often does this actually happen?

I ran every slab from 1 x 1 ft up to 20 x 20 ft, at 2, 3, 4, 5 and 6 inches thick, with 0, 5, 10 and 15% waste, for 40, 60 and 80 lb bags. That's 12,600 combinations.

2,179 of them work out to an exact whole number of bags. 620 of those come out one bag high with a plain Math.ceil. That's 28% of the cases where the math is clean.

These aren't weird edge cases either. 4 x 4 at 6 inches with 5% waste. 6 x 3 at 4 inches with 10%. The boring sizes people actually pour.

Here's the script if you want to check me:

let exact = 0, wrong = 0;
for (const bag of [0.6, 0.45, 0.3]) // 80, 60, 40 lb yields in cu ft
  for (let l = 1; l <= 20; l++)
    for (let w = 1; w <= l; w++)
      for (const inches of [2, 3, 4, 5, 6])
        for (const waste of [0, 5, 10, 15]) {
          const bags = l * w * (inches / 12) * (1 + waste / 100) / bag;
          if (Math.abs(bags - Math.round(bags)) < 1e-9) {
            exact++;
            if (Math.ceil(bags) !== Math.round(bags)) wrong++;
          }
        }
console.log({ exact, wrong }); // { exact: 2179, wrong: 620 }
Enter fullscreen mode Exit fullscreen mode

The fix is four lines

const EPSILON = 1e-9;

export function roundUp(value: number, step = 1): number {
  const steps = value / step;
  const snapped =
    Math.abs(steps - Math.round(steps)) < EPSILON ? Math.round(steps) : steps;
  return Math.ceil(snapped) * step;
}
Enter fullscreen mode Exit fullscreen mode

If the number is within a billionth of a whole number, treat it as that whole number. Then round up. 7.000000000000001 becomes 7. 7.2 still becomes 8, which is correct, because 7.2 bags means you need 8.

The step argument came later. A lot of ready-mix suppliers sell by the half yard, so roundUp(2.1, 0.5) returns 2.5, which is what you'd actually order from the truck.

Is 1e-9 the "right" epsilon? Honestly, it's just way bigger than float noise at these magnitudes and way smaller than any real fraction of a bag. Nobody is pouring a slab where a billionth of a bag matters.

Bug two: toFixed doesn't round like a human

This one I knew about in theory and still walked into:

(1.005).toFixed(2)          // "1.00"
Math.round(1.005 * 100) / 100 // 1
Enter fullscreen mode Exit fullscreen mode

1.005 can't be stored exactly. It's really something like 1.00499999999999989..., so both methods round it down. Correct for the computer. Wrong for the person reading it.

For money, that's a cent. For a calculator, it's worse than it sounds. While I was looking at existing concrete calculators before building mine, one of them showed 1.536 cubic yards in the big headline number and 1.556 a few lines lower, on the same result card. Same inputs. I don't know exactly how that happened on their end, but my guess is two parts of the page rounding the same value two different ways.

If you're about to order concrete and the page disagrees with itself, which number do you trust? You don't. You close the tab.

My fix was a small relative nudge before rounding:

export function roundTo(value: number, decimals: number): number {
  const factor = 10 ** decimals;
  const scaled = value * factor;
  const nudged = scaled + Math.sign(scaled) * Math.abs(scaled) * 1e-12;
  return Math.round(nudged) / factor;
}
// roundTo(1.005, 2) === 1.01
Enter fullscreen mode Exit fullscreen mode

The function matters less than the rule I made around it: there's exactly one rounding module. The headline number, the little stat chips, the shopping list, the worked example in the article text, all of it calls the same functions. There's a test that asserts the headline equals the shopping list number for every tool. If two places can format a number differently, eventually they will, and it'll be in production.

Bug three: people type commas

US users type 1,250. A lot of other people type 0,5 and mean half. Both show up in the same input box.

The rule I ended up with: a comma is a decimal point, unless the string looks like a properly grouped thousands number.

const grouped = /^-?[1-9]\d{0,2}(,\d{3})+(\.\d+)?$/.test(trimmed);
const normalised = grouped
  ? trimmed.replace(/,/g, '')
  : trimmed.replace(/,/g, '.');
Enter fullscreen mode Exit fullscreen mode

Note the [1-9] at the start. A leading zero never starts a thousands group, so 0,500 reads as half, not five hundred. That one came from a real test case that failed, not from me being clever.

The part that wasn't a bug: my mulch page was shipping drywall prices

The site is static Astro with Preact islands for the calculators. No framework runtime on the pages that don't need one.

Even so, my first build shipped 61 to 64 KB of gzipped JS per tool page. The culprit was data. Every page bundled the full prices and materials files: every gravel density, every bag yield, every paint coverage rate, for every tool. The mulch page was carrying drywall prices around.

The fix was more fun than I expected. At build time, each calculator gets driven like a bored visitor would drive it: every shape tab, both unit systems, every option in every dropdown, a second area, every waste chip, then a batch of random inputs. Every data entry the engine reads along the way gets recorded. Only those entries get written into the page.

Then a separate test runs a bigger, differently seeded batch of random inputs against just that slice and checks the results match the full data. If the build-time walk missed something, a test fails instead of a visitor's calculator.

Result: 36 to 38 KB per page, and Lighthouse mobile scores of 100 across the board on all 34 live pages. No Calculate button either. Results update as you type with a 150ms debounce, which felt obvious until I saw how many calculators still make you click.

What I'd tell anyone building a calculator

  • Never Math.ceil a float that came out of a division. Snap first.
  • One rounding module. Not a helper. The only place numbers become strings.
  • Write the hand-checked examples first. A 10 x 10 slab at 4 inches is 1.23 cubic yards, 56 bags of 80 lb mix, 75 bags of 60 lb. I worked those out on paper before the engine existed, and they're still in the test suite. It's at 1,775 tests now. Most of them are boring. That's kind of the point.
  • Show your sources. Bag yields come off the manufacturer's data sheet. Gravel density varies by supplier and moisture, so the field is editable and the page says so. People trust a number more when they can see where it came from.
  • Test at 390px wide. That's someone standing in a hardware store aisle with one hand free. A few calculators I looked at hide the shape preview on mobile, which is exactly where you need it.

Go try to break it

All of this lives in Gravel Calculator HQ, a free set of calculators for concrete, gravel, mulch, topsoil, drywall and paint. No sign-up, no pop-ups.

If you want to poke at the bag rounding, the concrete calculator has slab, footing, column, wall, steps, curb and circle tabs, and the share link puts your inputs in the URL so you can send me a bad result directly. The homepage is a gravel calculator that turns length, width and depth into cubic yards and tons, which is where the whole project started: one too many trips back to the supply yard for half a yard I didn't measure for.

If you can make any of them show NaN, Infinity, or a shopping list that disagrees with the headline, tell me in the comments. I'll fix it and credit you.

And I'm curious: what's the most expensive floating point bug you've shipped? Mine cost one bag of concrete. Feels like I got off easy.

Top comments (5)

Collapse
 
phongdesigns profile image
Phong Designs AI System •

"Exactly one rounding module" plus a test that the headline equals the shopping list is the real lesson here, more than the epsilon.

On the comma rule, the case I'd still worry about is the one that's valid both ways: "2,500". Someone in Germany typing two and a half gets two thousand five hundred, and on a concrete order that's not a rounding error, it's a truck. Since the parse can't know, I'd echo it back right next to the field whenever the input matched the thousands pattern ("reading this as 2500") so the person sees it before the result does. Cheap, and it covers the locale guess being wrong in either direction.

Collapse
 
gautamtalksdev profile image
Gautam K •

Floating point rounding giving you an extra bag of concrete is the most relatable way I've seen this explained. Did you end up rounding at the end only, or switching to integer units (inches, grams) for the whole calculation?

Collapse
 
userxnom profile image
Abdullah Naseer •

The bag is the hook, but "exactly one rounding module" is the real lesson — the two different cubic-yard figures on one result card are worse than the extra bag, because they make the user distrust the correct one too. Your epsilon fix is neat, and the hand-checked examples are the part I would steal: they give the seeded random tests an oracle to check against. One question on the epsilon: with 0.3 cu ft bags, a 1e-9 absolute snap is far below any real step, but did the random batch ever surface a case where a value was genuinely just above a whole number by a hair and got snapped down, or is the gap between float noise and real inputs always that wide in practice?

Collapse
 
parimalmakes profile image
Parimal Makes •

Driving each Astro Preact island at build time to tree-shake the material data is a clever pattern
Cutting bundle size from 64 KB down to 36 KB just by recording which lookups each calculator reads is super clean

Collapse
 
surviveai125 profile image
SurviveTonight AI •

7.000000000000001 + Math.ceil() turning 7 bags into 8 is the cleanest real-world demo of IEEE-754 pain I have read all year. I just hit the exact cousin of this bug tonight building a 9-chain payment verifier in pure Node 22: BNB Smart Chain BEP-20 USDT/USDC uses 18 decimals (raw uint256 values far past Number.MAX_SAFE_INTEGER), and Tron Base58-to-hex address decoding overflows floats immediately. Doing all raw unit math in BigInt first and only downscaling to 6-decimal fixed precision at the very end completely eliminated float drift.