9

This JavaScript code returns 115.3:

function FV(rate, nper, pmt, pv, type) {
    var pow = Math.pow(1 + rate, nper);
    var fv;
    if (rate) {
        fv = (pmt*(1+rate*type)*(1-pow)/rate)-pv*pow;
    } else {
        fv = -1 * (pv + pmt * nper);
    }
    return fv.toFixed(2);
}

document.write(   FV(0.06/12,12,-(2750+1375)/12,-0,0)-(0+2750+1375)    )

This Java code returns 106.1:

public double FV(double rate, double nper, double pmt, double pv, int type) {
    double pow = Math.pow(1 + rate, nper);
    double fv;        
    if (rate > 0) {
        fv = (pmt*(1+rate*type)*(1-pow)/rate)-pv*pow;
    } else {
        fv = -1 * (pv + pmt * nper);
    }
    return fv;
}
System.out.println(FV(0.06/12,12,-(2750+1375)/12,-0,0)-(0+2750+1375));

They look the same to me, but they return different values. What's wrong?

3
  • 3
    Default type of Java integer literals int and int devision round up the value. whereas in javascript devision operator return value dynamically, ex. 1 / 2 // returns 0.5 in JavaScript and 1 / 2 // returns 0 in Java Commented May 7, 2015 at 17:01
  • 1
    @SubhrajyotiMajumder Integer division rounds towards zero. The JLS says this about it: Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d · q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs. Commented Jul 8, 2015 at 18:07
  • I am saying same @kobit Commented Jul 9, 2015 at 4:11

1 Answer 1

26

In JavaScript -(2750+1375)/12 evaluates to -343.75. In Java it evaluates to -343, because in Java when you divide integer numbers, you get integer result. To fix this simply replace the expression with -(2750+1375)/12.0.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.