Menu

The loan payment formula returns NaN at 0% interest (and quietly breaks near it)
📰

The loan payment formula returns NaN at 0% interest (and quietly breaks near it)

DEV Community: webdev·MultiCalify·about 3 hours ago
#pj0sUa3a
#devtowebdev#devto#dev#rate#enter
Reading 0:00
15s threshold

Every loan payment function starts with the same formula, and almost every tutorial version breaks on a 0% promotion. Zero-interest financing is common enough, so that matters.

Here is the formula, the failure, and a version that holds up. All outputs below are from Node 24.

The standard formula

For a principal P , monthly rate r and n payments:

function pmtNaive ( P , apr , n ) { const r = apr / 1200 ; // annual percent -> monthly decimal const f = Math . pow ( 1 + r , n ) ; return P * r * f / ( f - 1 ) ; }

Enter fullscreen mode

Exit fullscreen mode

It works for normal rates:

pmtNaive ( 12000 , 7 , 24 ) ; // 537.2709492377435

Enter fullscreen mode

Exit fullscreen mode

That matches what you would expect for a $12,000 loan over 24 months at 7%. Now try a 0% deal:

pmtNaive ( 12000 , 0 , 24 ) ; // NaN

Enter fullscreen mode

Exit fullscreen mode

With r = 0 , the numerator is P * 0 * 1 = 0 and the denominator is 1 - 1 = 0 . You get 0 / 0 , which is NaN .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.