Skip to main content

Formatting rupees in JavaScript: lakhs and paise

8 min read
JavaScript
TypeScript
Internationalization
Testing
SC
Written by Shailesh Chaudhari
Full-stack engineer with a backend focus

To format Indian rupees in JavaScript, build one Intl.NumberFormat("en-IN", { style: "currency", currency: "INR", minimumFractionDigits: 2, maximumFractionDigits: 2 }), construct it once, and send every amount through it. That gives you ₹12,34,567.00 with lakh grouping and exactly two decimals, on every machine. Never call toLocaleString() with no locale for money: the grouping then comes from the viewer's browser, not from your app.

const INR = new Intl.NumberFormat("en-IN", {
  style: "currency",
  currency: "INR",
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});

export function formatInr(amount: number | string): string {
  const value = typeof amount === "string" ? parseFloat(amount) : amount;
  return INR.format(Number.isFinite(value) ? value : 0);
}

That is the whole of lib/money.ts in KhataGO, minus the comment block. The comment block is longer than the code, because the code is the easy part. Here is why it exists.

What broke

KhataGO is a bookkeeping app for Indian shop owners. It prints money in about thirty places in the code, across the dashboard, the receivables table, the analytics charts, monthly reports, invoices and the WhatsApp replies the agent sends. lib/utils.ts had exported a formatCurrency helper from early on. One page called it.

Everywhere else, amounts were rendered by hand. Two real lines from the old source:

₹{receivable.balance.toLocaleString("en-IN")}   // app/receivables
₹{data.totalSales.toLocaleString()}              // components/AnalyticsCharts

Both look like formatting. Neither is a contract.

toLocaleString has no opinion about fraction digits. It prints whatever precision the number happens to carry. So a balance of 1234.5 rendered as ₹1,234.5 in the receivables table, and the invoice built from the same row said ₹1,234.50. A round 5000 rendered as ₹5,000 with no decimals at all, one row above a ₹1,234.5. A column where the number of decimals changes per row is a column nobody can scan.

Then the GST-inclusive figures. Extracting 18% tax out of a total leaves you with numbers like 45.005. toLocaleString("en-IN") printed ₹45.005. Three decimal places, in a currency that has two.

The second line above is the worse one, and it is worse in a way that is easy to miss in review. There is no locale argument. That means the grouping comes from the browser the page is being read in. An Indian shop owner on a US-English browser saw ₹1,234,567 on the analytics page and ₹12,34,567 on every other page in the app, for the same number. Nothing threw. Nothing logged. On my machine, with my locale, it was fine. It was only wrong on other people's machines.

On top of that, three more files each declared their own new Intl.NumberFormat("en-IN", …): the dashboard, the monthly report, the transactions table. They agreed with each other by coincidence. Four formatters that agree today are four formatters that can be changed one at a time.

Why nobody reported it

Nothing was wrong enough to report. Every page looked fine on its own. The useful question for code like this is: what would have to be true for this to be wrong, and is anything checking that? For toLocaleString() the answer is "the reader is not in India", and no test checked that.

The fix

One module, one function, one contract: ₹, lakh grouping, exactly two decimals, and ₹0.00 rather than ₹NaN when a Prisma Decimal arrives as an unparseable string across a JSON boundary. Every display site and every outbound WhatsApp message goes through it. formatCurrency (lib/utils) and formatMoney (lib/metrics) still exist, but as aliases, so no caller had to change.

The unit tests pin the contract:

expect(formatInr(1234.5)).toBe("₹1,234.50");
expect(formatInr(5000)).toBe("₹5,000.00");
expect(formatInr(45.005)).toBe("₹45.01");
expect(formatInr(100000)).toBe("₹1,00,000.00");
expect(formatInr("not a number")).toBe("₹0.00");

With style: "currency" and INR, Intl already defaults to two fraction digits, so 5000 becomes ₹5,000.00 and 45.005 becomes ₹45.01 even without the two options. I set both anyway, so the contract is written in the code and not left to a currency table. The locale string "en-IN" is what gives you lakhs instead of thousands, and naming it is what stops the browser from choosing.

The test that keeps it fixed

Those assertions are not the important test. They passed before the fix too. The old formatCurrency was already correct; the problem was that nobody used it. A test that pins a helper's output proves the helper is right and says nothing about whether anyone calls it.

So the test that matters reads the source. It walks app/, components/ and lib/, and fails on a ₹ sitting within a short span of a toLocaleString:

for (const m of src.matchAll(/₹[^\n]{0,80}?toLocaleString/g)) {
  offenders.push(`${rel}:${line}`);
}
expect(offenders).toEqual([]);

That is the shape every one of the divergent sites had. A new one will fail CI rather than quietly diverge. There is also a guard that the scan found more than fifty files, because a source scan that stops finding files starts passing for the wrong reason.

I wrote more about this class of test in A passing test only proves the test passes. Centralising something is only done when nothing can still go around it, and only a check on the source can tell you that.

The GST split that gained a paisa

Formatting was the second money bug in this codebase. The first was in the invoice, and it is the one people search for.

An intra-state invoice in India shows GST as two lines, CGST and SGST, each half the tax. The old invoice page did the obvious thing:

cgst = totalGst / 2;
sgst = totalGst / 2;

and then rendered each through a two-decimal formatter. Take a tax of ₹45.01. Half is 22.505. The formatter rounds that to ₹22.51, on both lines. CGST ₹22.51 + SGST ₹22.51 = ₹45.02. One paisa more tax than the invoice's own total, printed on the same page. An accountant entering that invoice into Tally or a GST return would find its tax lines don't add up to its own tax total.

The fix is to round one leg and derive the other as the remainder, so the two always reconstruct the total:

export function splitGst(gstAmount: number, isInterState: boolean): TaxSplit {
  const total = toPaise(gstAmount);
  if (total <= 0) return { cgst: 0, sgst: 0, igst: 0 };
  if (isInterState) return { cgst: 0, sgst: 0, igst: total };

  const cgst = toPaise(total / 2);
  // Remainder, not a second independent rounding — guarantees cgst+sgst==total.
  const sgst = toPaise(total - cgst);
  return { cgst, sgst, igst: 0 };
}

toPaise is Math.round((value + Number.EPSILON) * 100) / 100. The epsilon nudge is there because 1.005 is stored as 1.00499… and would otherwise round down. The test for splitGst sweeps every paisa value from 0.01 to 50.00 and asserts cgst + sgst equals the input for each one. For 45.01 specifically it asserts CGST 22.51 and SGST 22.50.

The same pull request fixed a second GST error I would not have found without an integration test that parsed a real invoice: POST /api/transactions computed the tax with the tax-exclusive formula (amount × rate / 100) while storing the amount as tax-inclusive. A ₹2,100 sale at 5% printed taxable value ₹1,995 and tax ₹105, and 1,995 × 5% is 99.75, not 105. Now every write path goes through calculateGst, which extracts the tax out of an inclusive amount, and the invoice page states in a comment that amount is always the inclusive total.

What to do in your own code

Make one formatter and construct it once at module scope. Intl.NumberFormat costs more to build than to call, and a formatter inside a render function is a formatter you will copy.

Set both minimumFractionDigits and maximumFractionDigits. The currency style defaults to two for INR, but a plain number formatter does not: new Intl.NumberFormat("en-IN", { maximumFractionDigits: 2 }) prints 5000 as 5,000. Writing both down means nobody has to know which default applies.

Name the locale. If you ever see toLocaleString() next to a currency symbol, that number is different per reader.

Split money by rounding one side and subtracting. Never round two halves independently. This applies to any split, not only GST: commissions, tips, partial refunds.

Keep the pre-tax and post-tax convention in one place and state it. Two write paths that disagree about whether amount includes tax produce invoices that contradict themselves, and no unit test on either path will notice.

Then write the test that grep-scans your source for the shape of the defect. The helper being correct is not the property you care about. The property is that nothing goes around it.

SC
Written by Shailesh Chaudhari
Full-stack engineer with a backend focus