DEV Community

Build a Receipt Generator in JavaScript Without Float Bugs

Receipts look simple. A few items, a tax line, a total. Then you add up 19.99 three times, apply tax, and your total is off by a cent.

In this post I'll build a small receipt generator in plain JavaScript. No libraries. It handles money correctly, numbers each receipt, and prints cleanly on a phone or a thermal-style 80mm page.

The problem: floats and money

Run this in your console:

0.1 + 0.2 // 0.30000000000000004
1.15 * 100 // 114.99999999999999

JavaScript stores decimals as binary floats. Most decimal prices can't be stored exactly, and the errors pile up when you multiply by quantity and apply tax.

The fix is simple: store money as integer cents, and convert only for display.

Step 1: Money helpers

export const toCents = (amount) => Math.round(Number(amount) * 100);

export function formatMoney(cents, currency = "USD", locale = "en-US") {
  return new Intl.NumberFormat(locale, { style: "currency", currency }).format(cents / 100);
}

Intl.NumberFormat handles currency symbols, separators and decimal rules for you. Don't build that by hand.

Step 2: Calculate the receipt

export function buildReceipt({ items, taxRate = 0, discountCents = 0 }) {
  const lines = items.map(({ name, qty, price }) => {
    const unitCents = toCents(price);
    return { name, qty, unitCents, totalCents: unitCents * qty };
  });
  const subtotal = lines.reduce((sum, l) => sum + l.totalCents, 0);
  const taxable = Math.max(subtotal - discountCents, 0);
  const tax = Math.round(taxable * taxRate);
  return { lines, subtotal, discount: discountCents, tax, total: taxable + tax };
}

Two decisions here matter:

  • Round once. I round tax a single time on the taxable amount, not per line. Rounding per line can drift from the total by a few cents.
  • Apply the discount before tax. Check your local rules, because some places tax the pre-discount price.

Step 3: Number every receipt

export function receiptNumber(date, sequence) {
  const d = date.toISOString().slice(0, 10).replaceAll("-", "");
  return `RCP-${d}-${String(sequence).padStart(4, "0")}`;
}

This gives you RCP-20261127-0042. The date makes it readable, and the sequence keeps it unique.

Don't use Math.random() for receipt numbers. You'll get collisions, and your records won't be in order.

Step 4: Try it

const items = [
  { name: "Pipe fitting", qty: 3, price: 19.99 },
  { name: "Labor (1 hr)", qty: 1, price: 85 },
  { name: "Sealant", qty: 2, price: 4.5 },
];

const receipt = buildReceipt({ items, taxRate: 0.08, discountCents: toCents(5) });
console.log(receipt);

Output:

{ subtotal: 15397, discount: 500, tax: 1192, total: 16089 }

That's $153.97 subtotal, $5.00 off, $11.92 tax and a $160.89 total. The numbers check out: 15397 − 500 = 14897, and 8% of that is 1191.76, rounded to 1192.

Step 5: Render it as text

Here's a fixed-width version that works for logs, emails or a thermal printer preview:

export function renderText(receipt, number, currency = "USD") {
  const w = 32;
  const row = (l, r) => l.padEnd(w - r.length) + r;
  const out = [number, "-".repeat(w)];
  for (const l of receipt.lines) {
    out.push(row(`${l.qty} x ${l.name}`, formatMoney(l.totalCents, currency)));
  }
  out.push("-".repeat(w));
  out.push(row("Subtotal", formatMoney(receipt.subtotal, currency)));
  if (receipt.discount) out.push(row("Discount", "-" + formatMoney(receipt.discount, currency)));
  out.push(row("Tax", formatMoney(receipt.tax, currency)));
  out.push(row("TOTAL", formatMoney(receipt.total, currency)));
  return out.join("\n");
}

Output:

RCP-20261127-0042
--------------------------------
3 x Pipe fitting           $59.97
1 x Labor (1 hr)           $85.00
2 x Sealant                 $9.00
--------------------------------
Subtotal                  $153.97
Discount                   -$5.00
Tax                        $11.92
TOTAL                     $160.89

Step 6: Print it from the browser

You don't need a PDF library for a basic receipt. Render the text into a <pre> element and let the browser print it:

<pre id="receipt"></pre>
<button id="print">Print receipt</button>
import { buildReceipt, renderText, receiptNumber, toCents } from "./receipt.js";
const r = buildReceipt({ items, taxRate: 0.08, discountCents: toCents(5) });
document.getElementById("receipt").textContent = renderText(r, receiptNumber(new Date(), 42));
document.getElementById("print").onclick = () => window.print();
@page { size: 80mm auto; margin: 4mm; }
@media print {
  body * { visibility: hidden; }
  #receipt, #receipt * { visibility: visible; }
  #receipt { position: absolute; left: 0; top: 0; font: 12px/1.4 monospace; }
}

I used textContent, not innerHTML. Item names often come from user input, and innerHTML would let someone inject HTML into your receipt.

Users can also choose "Save as PDF" in the print dialog, so you get PDF export without extra code.

Pitfalls I'd watch for

  • Inputs with more than two decimals. toCents("1.005") returns 100, not 101, because of the same float issue. Limit price inputs to two decimals, or parse the string yourself.
  • Tax-inclusive prices. Many regions show prices with tax included. The math is different: tax = total - total / (1 + rate). Add a flag for it.
  • Currencies without cents. Yen has no minor unit. Look up the currency's decimal places before you hard-code * 100.
  • Storing floats in your database. Store integer cents or a DECIMAL type, never FLOAT.
  • Skipping tests. Write a few unit tests with known totals. Receipt bugs show up as angry customers, not error messages.

What to build next

  • A QR code on the receipt that links to a digital copy
  • Multiple tax rates per line item
  • Saving receipts to localStorage so users can reprint them

If you want to see a finished version of this idea, I built one here: my receipt maker.

What would you add? I'd like to hear how you handle tax rounding in your own projects.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.