如何计算利息 javascript

How to calculate interest javascript

我正在尝试创建一个函数,returns 我拥有的钱在 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 interest:

两边不需要括号
var calculateInterest = function (total,year,rate) {
    var interest = rate/100+1;
    return parseFloat((total*Math.pow(interest,year)).toFixed(4));
}

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

我建议稍微清理一下:

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:here