javascript.plainenglish.io 4 min read Original Source

Handling Money in JavaScript: Why 0.1 + 0.2 Can Cost You Real Rupees

Open your browser console and type this:

0.1 + 0.2
// 0.30000000000000004
0.1 + 0.2
// 0.30000000000000004

Most JavaScript developers have seen this meme. Fewer have seen what it looks like in a production payments system, where that tiny 0.00000000000000004 turns into a failed reconciliation, a wallet balance that’s off by a paisa, or a support ticket from a customer asking why their refund was ₹99.99 instead of ₹100.

I work on backend systems in fintech, and money handling is one of those things that looks trivial until it isn’t. Let’s walk through why JavaScript numbers betray you with money, and the patterns that actually work.

Why this happens

JavaScript has one number type for everyday math: Number, which is a 64-bit binary floating-point value (IEEE 754). Binary floating point can represent numbers like 0.5 and 0.25 exactly, because they’re powers of two. But it cannot represent 0.1 exactly, for the same reason you can’t write 1/3 exactly in decimal. You get 0.3333… forever, and at some point you have to cut it off.

So 0.1 in memory is really something like 0.1000000000000000055511151231257827. Add a few of those together and the errors surface:

a + b, 0);
// 0.6000000000000001
19.99 * 100;
// 1998.9999999999998″ data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

[0.1, 0.2, 0.3].reduce((a, b) => a + b, 0);
// 0.6000000000000001
19.99 * 100;
// 1998.9999999999998
[0.1, 0.2, 0.3].reduce((a, b) => a + b, 0);
// 0.6000000000000001
19.99 * 100;
// 1998.9999999999998

That second one is the dangerous kind. It looks like a harmless conversion from rupees to paise. It isn’t.

Where it bites in real apps

Converting user input to paise. A user types ₹19.99 into a payment form. You do parseFloat(input) * 100 and send 1998.9999999999998 to your payment gateway. Depending on the API, that’s either a validation error or a silently truncated ₹19.98.

Rounding for display. You’d expect toFixed to save you. It doesn’t:

(1.005).toFixed(2);
// "1.00"  (you expected "1.01")
Math.round(1.005 * 100) / 100;
// 1
(1.005).toFixed(2);
// "1.00"  (you expected "1.01")
Math.round(1.005 * 100) / 100;
// 1

1.005 is actually stored as 1.00499999999999989…, so it rounds down. Every “round to two decimals” helper built on this trick has the same flaw.

Summing many small amounts. Cashback, interest accruals, SIP instalments, split bills. Add a few thousand floating-point values and the drift becomes visible. Your ledger total no longer matches the sum your bank or partner reports, and now someone has to reconcile it by hand.

Comparisons. if (balance >= amount) can fail when balance is 99.99999999999999 and amount is 100. The user has the money. Your code says they don’t.

Fix #1: Store money as integers in the smallest unit

This is the single most important rule. Store and compute money in paise, not rupees. ₹19.99 becomes 1999. Integers are exact in JavaScript up to Number.MAX_SAFE_INTEGER, which is 9,007,199,254,740,991. In paise, that’s roughly ₹90 lakh crore, so you’re unlikely to hit the ceiling.

This isn’t just a JavaScript trick. Payment gateways like Razorpay and Stripe expect amounts in the smallest currency unit for exactly this reason.

javascript

const priceInPaise = 19900;        // ₹199.00
const gstInPaise = (priceInPaise * 18) / 100;  // 3582, exact
const totalInPaise = priceInPaise + gstInPaise; // 23482
const priceInPaise = 19900;        // ₹199.00
const gstInPaise = (priceInPaise * 18) / 100;  // 3582, exact
const totalInPaise = priceInPaise + gstInPaise; // 23482

Addition, subtraction, and comparison on integers are exact. The only place you need care is division and percentages, which we’ll get to.

Fix #2: Never convert input with parseFloat

If floating point is the problem, don’t pass through it at all. Parse the string directly into paise:

javascript

function toPaise(input) {
  const s = String(input).trim();
  if (!/^d+(.d{1,2})?$/.test(s)) {
    throw new Error(`Invalid amount: ${input}`);
  }
  const [rupees, paise = ''] = s.split('.');
  return Number(rupees) * 100 + Number(paise.padEnd(2, '0'));
}
toPaise('19.99'); // 1999
toPaise('5.5');   // 550
toPaise('100');   // 10000
function toPaise(input) {
  const s = String(input).trim();
  if (!/^d+(.d{1,2})?$/.test(s)) {
    throw new Error(`Invalid amount: ${input}`);
  }
  const [rupees, paise = ''] = s.split('.');
  return Number(rupees) * 100 + Number(paise.padEnd(2, '0'));
}
toPaise('19.99'); // 1999
toPaise('5.5');   // 550
toPaise('100');   // 10000

No floats, no rounding surprises, and you get input validation for free. Extend the regex if you need negative amounts or thousands separators.

Fix #3: Split amounts without losing a paisa

Here’s a classic: split ₹100 between three people.

javascript

10000 / 3; // 3333.3333333333335
10000 / 3; // 3333.3333333333335

Rounding each share to 3333 gives a total of ₹99.99. A paisa vanished. In a ledger, money can’t vanish, so distribute the remainder explicitly:

javascript

base + (i

function allocate(totalPaise, parts) {
  const base = Math.floor(totalPaise / parts);
  const remainder = totalPaise - base * parts;
  return Array.from({ length: parts }, (_, i) =>
    base + (i < remainder ? 1 : 0)
  );
}
allocate(10000, 3); // [3334, 3333, 3333]  → sums to 10000
function allocate(totalPaise, parts) {
  const base = Math.floor(totalPaise / parts);
  const remainder = totalPaise - base * parts;
  return Array.from({ length: parts }, (_, i) =>
    base + (i < remainder ? 1 : 0)
  );
}
allocate(10000, 3); // [3334, 3333, 3333]  → sums to 10000

The shares always add up to the original total. This matters for EMI schedules, bill splitting, and fee distribution between partners.

Fix #4: Use a decimal library when you need real precision

Integers in paise cover most e-commerce and wallet use cases. But some domains need more decimal places than currency does. Mutual funds are a good example: NAVs typically go to four decimal places and allotted units to three.

For that, use a decimal arithmetic library. decimal.js and big.js are the popular choices, and dinero.js is built specifically around money.

javascript

import Decimal from 'decimal.js';
const amount = new Decimal('5000');
const nav = new Decimal('123.4567');
const units = amount.div(nav).toFixed(3, Decimal.ROUND_DOWN);
// "40.500"
import Decimal from 'decimal.js';
const amount = new Decimal('5000');
const nav = new Decimal('123.4567');
const units = amount.div(nav).toFixed(3, Decimal.ROUND_DOWN);
// "40.500"

Two things to notice. First, the inputs are passed as strings, not numbers. new Decimal(0.1) would inherit the float error before the library even sees it. Second, the rounding mode is explicit. Whether you round down, round half-up, or use banker’s rounding is a business rule, and it should be visible in the code rather than hidden inside toFixed.

If you work across a Java backend and a JavaScript frontend, this is the JS equivalent of using BigDecimal with a RoundingMode instead of double.

Fix #5: Format only at the edges

Keep money as integers (or decimals) everywhere in your logic, and convert to a human-readable string only at the moment you display it. Intl.NumberFormat handles Indian grouping and the rupee symbol for you:

javascript

new Intl.NumberFormat('en-IN', {
style: 'currency',
currency: 'INR',
}).format(paise / 100);
formatINR(12345650); // "₹1,23,456.50"” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

const formatINR = (paise) =>
  new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR',
  }).format(paise / 100);
formatINR(12345650); // "₹1,23,456.50"
const formatINR = (paise) =>
  new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR',
  }).format(paise / 100);
formatINR(12345650); // "₹1,23,456.50"

Dividing by 100 here is fine because it’s display-only. The result never flows back into a calculation.

Fix #6: Be deliberate about money in your APIs

JSON numbers are parsed as JavaScript floats, so the same problem follows you across the network. A few habits help:

  • Send amounts as integers in paise ("amount": 1999) or as strings ("amount": "19.99"), never as float rupees.
  • Always send the currency alongside the amount, even if you only support INR today.
  • Document the unit in your API contract. amount_paise as a field name removes all ambiguity.

A quick checklist

Before your next feature that touches money ships, ask:

  1. Are amounts stored and computed as integers in the smallest unit?
  2. Is user input parsed from strings, not through parseFloat?
  3. Does any split or division distribute the remainder explicitly?
  4. Is a decimal library used, with string inputs, wherever more precision is needed?
  5. Is rounding mode an explicit, documented business rule?
  6. Does formatting happen only at the display layer?
  7. Do your APIs make the unit and currency unambiguous?

Wrapping up

0.1 + 0.2 is a funny meme until it’s your reconciliation report. The fix isn’t clever math. It’s discipline: integers for storage, strings for input, explicit rules for rounding and splitting, and formatting only at the edges.

Your users will never notice when you get this right. They’ll definitely notice when you don’t.

If this helped, follow me for more practical backend and fintech engineering from the trenches.