0

I have assigned 90071992547419999992 to a const variable 'a' and I'm trying to console its value. The compiler shows 90071992547420000000 as the answer. Why is the number getting rounded? Can anyone explain how overflow is handled in javascript?

const a = 90071992547419999992;
console.log(a);
console.log(typeof a);
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – evolutionxbox Sep 29 '22 at 09:06
  • That number is bigger than `Number.MAX_SAFE_INTEGER` – evolutionxbox Sep 29 '22 at 09:06
  • check out `const a = 90071992547419999992n;` *SO's console doesn't print them right. Either use `console.log(""+a)` or look at the browser console.* – Thomas Sep 29 '22 at 09:11
  • I do not think JavaScript has integer overflow. – evolutionxbox Sep 29 '22 at 09:13
  • @evolutionxbox But the above number is not a floating point number right? – Princy Ajit Sep 29 '22 at 09:18
  • @PrincyAjit yes it is. JS numbers are (in principle) always floating point numbers. – Thomas Sep 29 '22 at 09:20
  • @PrincyAjit *You didn't read the `typeof` that value*. It's because that is not a number anymore. It's a [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) – Thomas Sep 29 '22 at 09:26
  • @evolutionxbox technically not, but kind of? Ain't it an integer overflow that happens when you apply a bit-operation to a number that's outside the int32 number space? – Thomas Sep 29 '22 at 09:28

1 Answers1

0

One of the comment is right. It is bigger than the Number.MAX_SAFE_INTEGER which causes Javascript to break. You can do big operations than Number.MAX_SAFE_INTEGER by just adding a n at the last of the number or passing the number to BigInt('aabbcc') function, it will return a bigint number. It was introduced in ES2020, so it will not work in older versions.

const a = 90071992547419999992n;
console.log(a);
console.log(typeof a);
Divyansh
  • 1
  • 3
  • *"...which causes Javascript to break"* there's nothing broken here. Everything works exactly as intended and defined. It's just not intuitive. *"You can do big operations than Number.MAX_SAFE_INTEGER by just adding a n at the last of the number."* `const a = 90071992547419999.992n` throws a SyntaxError. so does `const a = 90071992547419999992n + 1;` – Thomas Sep 29 '22 at 09:36
  • @Thomas You need to convert 1 (which is a integer) to a bigint because you are doing operations with bigint. Which means const a = 90071992547419999992n + 1n; will not give any errors. – Divyansh Sep 29 '22 at 09:41