Search code examples
javascriptreturndecimal

Return 2 Decimal Places In Function Array


I would like to return an array of items to 2 decimal places.

Example- Return with 5 for "Enter years", 1000 for "Enter iniInvest", 10 for "Enter interest", and 1000 for "Enter yearlyInv": 1100,2310,3641,5105.1,6715.610000000001

I would like the array items to end in 2 decimal places. 1100.00, 2310.00, 3641.00, 5105.10, 6715.61

I have attempted a few things including

return totalArry.toFixed(2);
return totalArry[].toFixed(2);

Neither of these resolved the issue. I've done some searching but I don't understand enough to know how to convert some of the answers I found to work with my code.

function investCalc() {
    for(i=1; i<years; i++) {
        totalYear += parseFloat(yearlyInv); 
        totalInt = parseFloat(totalYear) * parseFloat(interest/100); 
        totalYear += parseFloat(totalInt); 
        totalArry.push(totalYear);
    }
    return totalArry.toFixed(2);
}
var years = prompt("Enter years");
var iniInvest = prompt("Enter iniInvest");
var interest = prompt("Enter interest");
var yearlyInv = prompt("Enter yearlyInv");
var totalInt = parseFloat(iniInvest) * parseFloat(interest/100); 
var totalYear = parseFloat(iniInvest) + parseFloat(totalInt); 
var totalArry = [totalYear]; 

alert(investCalc());

Any help is much appreciated.


Solution

  • If you want each element of the array to have 2 decimal places, you need to call .toFixed(2) on each element, not on the array variable. You can do it before you push an element to the array: totalArry.push(totalYear.toFixed(2));

    Note that toFixed returns a string, so you will get an array of strings. If you want an array of numbers, you can use the unary plus operator: totalArry.push(+totalYear.toFixed(2));

    function investCalc() {
        for(let i = 1; i < years; i++) {
            totalYear += parseFloat(yearlyInv); 
            totalInt = parseFloat(totalYear) * parseFloat(interest/100); 
            totalYear += parseFloat(totalInt); 
            totalArry.push(+totalYear.toFixed(2));
        }
        return totalArry;
    }
    var years = prompt("Enter years");
    var iniInvest = prompt("Enter iniInvest");
    var interest = prompt("Enter interest");
    var yearlyInv = prompt("Enter yearlyInv"); 
    var totalInt = parseFloat(iniInvest) * parseFloat(interest/100); 
    var totalYear = parseFloat(iniInvest) + parseFloat(totalInt); 
    var totalArry = [+totalYear.toFixed(2)]; 
    
    console.log(investCalc());