I have a fee, and I’m trying to calculate the installment amount of paying the fee in X installments. What I want is to round (or floor – I’m not sure about that spec yet) X-1 installments, and then calculate the last installment based on the remaining fee.
So I did the following, but the last installment has many integers. It’s a simple subtraction, why does it lose its precision?
Also, would you calculate the whole concept in a different way?
let tuitionFee = 1000;
let numberOfInstallments = 7;
let roundedInstallments = Math.round(tuitionFee / numberOfInstallments * 100) / 100;
let lastInstallment = tuitionFee - (roundedInstallments * (numberOfInstallments - 1));
console.log(tuitionFee / numberOfInstallments);
console.log(roundedInstallments);
console.log(lastInstallment);
2
Answers
Generally, floating point math should be arranged in a way that minimizes error. In this case, it makes sense to have pennies as the unit. This would reduce error by making it so that most calculations are applied to integers. So we modify it to do that and only convert to dollars for display.
You may use these 2 general functions: