If you have ever built a loan or mortgage calculator, you have probably shipped this bug: 0.1 + 0.2 in JavaScript is 0.30000000000000004, not 0.3. Display it raw and your calculator tells a user their payment is $313.36000000000003. Round only at display time and the error compounds across an amortisation schedule, so the final balance comes out a few cents off and the schedule never quite reaches zero.
Three rules that fix it in practice:
- Do money in integer cents (or a decimal type) until the very last step. Parse the input once, convert dollars to cents, and keep every intermediate value in cents. Only format back to dollars for display.
- Round each month's split, not just the total. Interest for a month is balance x monthly rate, rounded to the cent; principal is payment minus that rounded interest. If you round only the payment, the schedule drifts.
- Force the last payment to clear the balance. Take a $10,000 loan at 8% over 3 years: the payment is $313.36 a month, first month's interest is $66.67 and the total interest is $1,281.09. Compute the schedule month-by-month with the rules above and the final payment lands a few cents short of $313.36 — set it to whatever balance remains, and say so in the UI, instead of showing a phantom final balance.
The same discipline applies to the formula itself: use the standard amortisation formula, payment = P x r / (1 - (1 + r)^-n), with r the monthly rate and n the number of payments, and show the schedule so a user can check your arithmetic — a calculator nobody can audit is a calculator nobody trusts. Live examples of the rounding done this way: https://quickcalcify.com/loan-calculator and https://quickcalcify.com/mortgage-calculator
Top comments (0)