0

So, I found something I couldn't understand and can't find any internet resource that explains it.

Please see the code below:

var num = 35422484817926290

// subtract 5 from num
console.log(num-5)

Output (Wrong) : 35422484817926284

I checked it in Node, Opera, and Chrome, all of them give the wrong answers.

I do understand the fact that arithmetic with unsafe Integers in JS is faulty, for example:

console.log(100000000000000005-1)

Output (Wrong) : 100000000000000000

So what's the deal with big number arithmetic in JS?

Nick is tired
  • 6,860
  • 20
  • 39
  • 51
Kristie
  • 92
  • 8
  • any integer bigger than `Number.MAX_SAFE_INTEGER` is not going to work well, that's what `BigInt` is for - if you think xxx66e+307 + xxx22e+307 = xxx87e+307 is correct, then you have more problems than big numbers - hint: 66+22 = 88 – Bravo Aug 10 '21 at 12:47
  • Bug reports in JS - well, first, you have to know which JS engine you're talking about - then report it as appropriate – Bravo Aug 10 '21 at 12:53
  • "*I do understand the fact that arithmetic with unsafe Integers is faulty*" - well, do you? And no, it's not just JS. – Bergi Aug 10 '21 at 13:51

2 Answers2

0

When I run this code:

var num = 35422484817926290

// subtract 5 from num
console.log(num-5)

in Visual Studio Code, i get the following warning: "Numeric literals with absolute values equal to 2^53 or greater are too large to be represented accurately as integers."

So the correct way to make this calculation would be like this:

var num = 35422484817926290n

// subtract 5 from num
console.log(num-5n)
mokumus
  • 185
  • 1
  • 11
0

JavaScript is not faulty, this is how the Floating point arithmetic works. Looks duplicate to this post. For better calculation involving floating-point numbers you should use BigNumber API.

Chrome Console

nraina
  • 324
  • 2
  • 20