Member-only story
Splitting Money in JavaScript: Round Every Share and the Total Stops Adding Up
A ₹200 coupon over three cart lines gave away ₹200.01. Integer minor units fix the input. Allocating the remainder fixes the split.
Santosh Yadav
10 min read1 hour ago
Press enter or click to view image in full size
Put three items in a cart: ₹199, ₹299 and ₹799. Apply a ₹200 coupon and spread it across the lines by price, so each line shows its own discount. Round each share to the paisa, add them up, and you get ₹200.01.
Nobody will notice one paisa on a receipt. Your finance export will, because the order total no longer equals the sum of its lines, and that row gets flagged every time. Money rounding in JavaScript usually gets blamed on floating point. Floats are part of it, but this bug survives even when every number is a clean integer. It comes from rounding each share on its own.
So this post is about two decisions, made once each.…