Reputation: 452
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
Upvotes: 1
Views: 2211
Reputation: 109
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
Upvotes: 2
Reputation: 97227
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
Upvotes: 0
Reputation: 1526
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)
Upvotes: 3