1

Stuck with one problem

Does anyone have any idea why it getting such results?

let x = 4153000000000000000 + 99
console.log(x) // 4153000000000000000

let y = 4153000000000000000 + 990
console.log(y) // 4153000000000001000

let z = 4153000000000000000 + 9900
console.log(z) // 4153000000000009700

3 Answers3

3

So your problem is that the numbers you have used are larger than the maximum capacity of Integer which is 9007199254740991. Thus anything larger than 9007199254740991 will cause abnormal behaviour.

Use something like :

let x = BigInt("4153000000000000000")

let y = BigInt("1235")

let z = x + y;

document.write(z);
console.log(z)
Jaysmito Mukherjee
  • 1,467
  • 2
  • 10
  • 29
2

It is because of IEEE. Numbers above 2^53 need to be done with big Int.

The safest max number is

let a = Number.MAX_SAFE_INTEGER;
//console.log(9007199254740991);

and minimum number is

 let b = Number.MIN_SAFE_INTEGER;
 //console.log(-9007199254740991);

To solve this issue, we use BigInt;

let sum = 4153000000000000000n + 99n;
console.log(sum); // 4153000000000000099n

You can click here for more details. // MDN

More reference here //Stackoverflow

Hrushikesh Rao
  • 109
  • 1
  • 4
  • 2
    It's not "JavaScript numbers", its IEEE 754 numbers as implemented by the vast majority of modern computing platforms. You see exactly the same effects in most other programming languages. – Pointy Jan 08 '21 at 06:24
0

The result of your operation goes beyond the bounds of what can safely be represented by the JavaScript number type:

console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991

If you want to deal with larger numbers, you can use the built-in BigInt type:

const z = 4153000000000000000n + 9900n;
console.log(`Result: ${z}`); // 4153000000000009900
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156