Javascript 如何计算利息

Javascript 如何计算利息,javascript,math,Javascript,Math,我试图创建一个函数,返回我在x年利息后的钱 var calculateInterest = function (total,year,rate) { (var interest = rate/100+1; return parseFloat((total*Math.pow(interest,year)).toFixed(4)) } ANSWER = calculateInterest(915,13,2); 我不能让它工作,我被卡住了! 有什么

我试图创建一个函数,返回我在x年利息后的钱

    var calculateInterest = function (total,year,rate) {
        (var interest = rate/100+1;
         return parseFloat((total*Math.pow(interest,year)).toFixed(4))
    }

ANSWER = calculateInterest(915,13,2);
我不能让它工作,我被卡住了!
有什么建议吗?

你很接近了。var利息周围不需要括号:

我建议将其清理一点,以便:

var calculateInterest = function (total, years, ratePercent, roundToPlaces) {
    var interestRate = ((ratePercent/100) + 1);
    return (total * Math.pow(interestRate, years)).toFixed(roundToPlaces);
}

var answer = calculateInterest(915, 13, 2, 2);
如果变量已经是一个数字,则不需要parseFloat,在从字符串进行解析时需要它,而不是这里的情况。添加一个参数以指定要舍入的小数位数非常有用,这样可以控制函数的输出


更新的fiddle:

为什么在var前面有一个左括号?第二行欢迎使用堆栈溢出!仅供参考,让我们知道到底是什么卡住了是很有帮助的-您是否得到了任何错误、无效结果或其他东西?从财务角度来看,利息是如何复合的?例如,大多数抵押贷款按月复利,因为你按月付款。经常账户和信用卡可以每天复合。如果你得到的答案与你预期的稍有不同,可能是这样。或者是计算利息天数的方法,利息的变化很微妙。
var calculateInterest = function (total, years, ratePercent, roundToPlaces) {
    var interestRate = ((ratePercent/100) + 1);
    return (total * Math.pow(interestRate, years)).toFixed(roundToPlaces);
}

var answer = calculateInterest(915, 13, 2, 2);