0

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));
Karim Ali
  • 2,243
  • 6
  • 23
  • 31
  • 1
    I recommend to use integers for calculation and only use decimals for output. Using floating point arithmetic for money usually leads to rounding errors. – jabaa Jul 13 '23 at 22:36
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – jabaa Jul 13 '23 at 22:38
  • Just updated the code with RC. – Karim Ali Jul 13 '23 at 22:41
  • 1
    That's what I mean: https://jsfiddle.net/bgLur90t/ use integers for math and decimals for output. Not all floating point numbers are representable as IEEE 754 float or double, e.g. `0.1`. – jabaa Jul 13 '23 at 22:43
  • @jabaa txs. works. – Karim Ali Jul 20 '23 at 13:43

0 Answers0