0

I am trying to create a simple function that returns the sum of all the digits in a number (after power operation). The thing is, I am getting a weird result when working with really big numbers that use scientific notation.

I assume it's because of something with the Math.floor() method. But I did try to read on the docs if there is a problem using this method with big numbers and I didn't see such a warning.

My code looks like that:

function fixedPowerToString(num, pow) {
    let powResult = Math.pow(num, pow);
    let sum = 0;
    let result = powResult;
    while(result >= 10) {
       sum += result % 10;
       result = Math.floor(result / 10); 
    }
    sum += result;
    return sum;
}

console.log(fixedPowerToString(2, 1000)); // returns 1189 instead of 1366

when testing with smaller numbers it seems to be fine. So I assume it's because the number is too big to process correctly?

eliezra236
  • 547
  • 1
  • 4
  • 16
  • with large floating point numbers you also loose a lot of precision. It's not only `Math.floor` but also `%` and `/` which won't work accurately. The more operations you do, the more imprecise the numbers get. – Jonas Wilms Dec 22 '20 at 12:54
  • 1
    `Math.pow(2, 1000)` results in a number ***dramatically*** larger than the maximum integer value that can be held in a JavaScript number without loss of precision, which is 9,007,199,254,740,991. After that number, only even (not odd) numbers can be held. Further on, only multiples of 4. After that, only multiples of 8. And so on. You could hold the value in a [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt), though: `BigInt(2)**BigInt(1000)`. Then use `10n` for your `%` and `/` operations, and convert to number when adding to `sum`. – T.J. Crowder Dec 22 '20 at 12:58

0 Answers0