简体   繁体   中英

Financial calculation with JavaScript (What´s wrong?)

I'm trying to make a financial calculation, but there's something wrong.

JS Code:

function count (){

var coda = 1.500;
var codb = 15;
var codc = 0.06;
var codx = 1;

var result = (codc/codx(codx-((codx+codc)*-codb)))*coda;

alert(result);


}

Message: undefined

In this line var result = (codc/codx(codx-((codx+codc)*-codb)))*coda;

You try to execute the 2nd codx as a function ( codx() ). I guess you miss an operand there.

Try for example: var result = (codc/codx / (codx-((codx+codc)*-codb)))*coda;

You are missing a * operator, so the compiler tries to call codx as a function.

To fix your computation, add the * operator as follow:

function count (){

    var coda = 1.500;
    var codb = 15;
    var codc = 0.06;
    var codx = 1;

    var result = (codc/codx * (codx - ((codx+codc)*-codb)))*coda;
    //                      ^

    alert(result);
}

Missing * symbol? codx is being used as a fuction as a result.

 var coda = 1.500; var codb = 15; var codc = 0.06; var codx = 1; var result = (codc/codx*(codx-((codx+codc)*-codb)))*coda; alert(result);

Slightly off-topic but you should never use floating point arithmetic in financial calculations. Instead calculate by integer cents and then format for viewing as you like.

In this case,

It is better to split the mathematical calculation.

Example:

function count (){

var coda = 1.500;
var codb = 15;
var codc = 0.06;
var codx = 1;

var res1 = ((codx+codc)*-codb);
var res2 = codx-res1;
var result = (codc/codx*res2)*coda;

alert(result);

}
var count = function () {
 var coda = 1.5; var codb = 15; var codc = 0.06; var codx = 1;
 var result = (codc/codx ** here ** (codx-((codx+codc)* - codb))) *  coda;    
 console.log(result);
}  

PS you have to put something after codx it's seen by javascript as an undefined function.

If this relates to paying down a loan at interest i per payment period, then you get that after n payments at a rate of r the reduced principal is

p*(1+i)^n-r*(1+i)^n-r*(1+i)^(n-1)-...-r*(1+i) 
=
p*(1+i)^n - (1+i)*((1+i)^n-1)/i*r

If that is to be zero, loan repaid, then the necessary rate computes as

r = i/((1+i)*(1-(1+i)^(-n))) * p

which is in some aspects similar, in other fundamental aspects different from your formula.

 var p = 1.500; var n = 15; var i = 0.06; var x = 1+i; var result = i/( x*( 1-Math.pow(x,-n) ) )*p; alert(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM