How can I calculate the last payment for Reprofiled Amount column with 2 decimal places to make the sum of all payments to be the same as RC amount?

How can I calculate the last payment for Reprofiled Amount column with 2 decimal places to make the sum of all payments to be the same value as Research Costs amount? The difference needs to be added to the last quarterly payment.

I have 3 payment values stored in numAmounts array. Const numAmounts = [ 106017.96, 106017.96, 106017.96 ]; My code to calculate the last payment gives me 106017.96999999997 but when I pass value to my formatAsCurrency(remainningAmount, 2, 2) I get 106017.96 which if we sum all 3 numAmounts values + remainningAmount there is a difference of 1 cent. That 1 cent needs to be added to the last quarterly payment.

function formatAsCurrency(numValue, numMinimumDigits, numMaximumDigits)
        {
            try
            {
                if (!numMinimumDigits || isNaN(numMinimumDigits))
                {
                    numMinimumDigits = 0;
                }

                numValue = Number(numValue.toString().replace(/[^0-9.-]/g, ""));
                if (!isNaN(numValue))
                {
                    if (!numMinimumDigits || numMinimumDigits <= 0)
                    {
                        return Number(numValue.toFixed(0)).toString();
                    }
                    else
                    {
                        return numValue.toLocaleString("en-US", { minimumFractionDigits: numMinimumDigits, maximumFractionDigits: numMaximumDigits });
                    }
                }
                else
                {
                    return numValue;
                }
            }
            catch (ex)
            {
                alert("Error in formatAsCurrency(): " + ex.toString());
                disableAll();
                return false;
            }
        }
const RC = 424071.85;      
const numAmounts =  [ 106017.96, 106017.96, 106017.96 ];
const sum = numAmounts.reduce((acc, curr) => acc + curr, 0);
const remainningAmount = RC - sum;
console.log("remainningAmount", formatAsCurrency(remainningAmount, 2, 2));

Okay… 6 am. blinks several times at post, puts second paragraph first, tries to read again

right. So floating point errors. You should account for that.
remainingAmount = (RC - sum).toFixed(2)

1 Like

Txs. It works. Appreciated.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.