Bifalgorithm post · Computer science one · Paying the Piper

How can a PHP program calculate and round a monthly loan payment?

How can a PHP program calculate and round a monthly loan payment? (Computer science one · Paying the Piper) — "Let’s adapt the solution for the loan amortizati…

Ideas in this flowchart

  • Adaptation of the loan amortization schedule
  • Read the principal, terms, and interest as command-line inputs.
  • Calculate the monthly payment with the adapted amortization formula.
  • Use the standard math library’s pow() function in the formula.
  • Round all currency figures to the nearest cent for accuracy.
  • The standard round() function rounds only to the nearest whole number.
  • Multiply the amount by 100, round it, and divide it by 100.
  • For example, 43.871 becomes 4387.1, then 4387, and finally 43.87.
  • Apply the same rounding method to monthly interest and other whole-cent amounts.
  • Use printf() to output the numbers with aligned columns.
  • Handle the final month separately to correct an overpayment or underpayment caused by rounding.
Feed/

How can a PHP program calculate and round a monthly loan payment?

No cover

Channel

Computer science one

1 page

"Let’s adapt the solution for the loan amortization schedule we developed in Section 4.7.3. First, we’ll read the principle, terms, and interest as command line inputs. Adapting the formula for the monthly payment and using the standard math library’s pow() function, we get\n\n$monthlyPayment = ($monthlyInterestRate * $principle) /\n\n(1 - pow( (1 + $monthlyInterestRate), -$n));\n\nThe monthly payment may come out to be a fraction of a cent, say $43.871. For accuracy, we need to ensure that all of the figures for currency are rounded to the nearest cent. The standard math library does have a round() function, but it only rounds to the nearest whole number, not the nearest 100th. However, we can adapt the “off-the-shelf” solution to fit our needs. If we take the number, multiply it by 100, we get 4387.1 which we can now round to the nearest whole number, giving us 4387. We can then divide by 100 to get a number that has been rounded to the nearest 100th!\n\n$monthlyPayment = round($monthlyPayment * 100) / 100;\n\nWe can use the same trick to round the monthly interest payment and any other number expected to be whole cents. To output our numbers, we use printf() and take care to align our columns to make make it look nice. To finish our adaptation, we handle the final month separately to account for an over/under payment due to rounding."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.