Microsoft Excel FV function in Java

FV, one of the financial functions, calculates the future value of an investment based on a constant interest rate. You can use FV with either periodic, constant payments, or a single lump sum payment.

Syntax
FV(rate,nper,pmt,[pv],[type])
The syntax has the following arguments:

Rate:- Required. The interest rate per period.
Nper:- Required. The total number of payment periods in an annuity.
Pmt:- Required. The payment made each period; it cannot change over the life of the annuity. Typically, pmt contains principal and interest but no other fees or taxes. If pmt is omitted, you must include the pv argument.
Pv:- Optional. The present value, or the lump-sum amount that a series of future payments is worth right now. If pv is omitted, it is assumed to be 0 (zero), and you must include the pmt argument.
Type:- Optional. The number 0 or 1 and indicates when payments are due. If type is omitted, it is assumed to be 0.
           0 - At the end of the period
           1 - At the beginning of the period

The Java equivalent function is:


static public double fv(double r, int nper, double pmt, double pv, int type) {        double fv = -(pv * Math.pow(1 + r, nper) + pmt * (1 + r * type) * (Math.pow(1 + r, nper) - 1) / r);        return fv;    }

A high precision version using BigDecimal will be:


static public BigDecimal fv(BigDecimal intRate, int nper, BigDecimal pmt, BigDecimal pv, int type) {        BigDecimal fvPositive = (pv.multiply((ONE.add(intRate)).pow(nper)))                .add(pmt                        .multiply(ONE.add(intRate.multiply(BigDecimal.valueOf(type))))                        .multiply(((ONE.add(intRate)).pow(nper)).subtract(ONE))                        .divide(intRate, DECIMAL_SCALE, DECIMAL_ROUNDING_MODE)                );        return fvPositive.negate();    }

Full source code can be found at: ExcelFunctions.java

0 comments:

Post a Comment