0

I was doing some problems on Leetcode, this one in particular, and I noticed some oddities with how JavaScript handles bigger numbers:

> x = 1000000000000000000000000000001;
1e+30 // Scientific notation? interesting

> x.toString()
'1e+30' // Reason for the parsing issues with my Leetcode implementation..

> x.toLocaleString('en', { useGrouping: false });
'1000000000000000000000000000000' // The last '1' was changed to a '0', probably cause x is stored as 1e+30.

> BigInt(x).toString();
'1000000000000000019884624838656' // ?

> y = 2384762348723648237462348;
2.3847623487236483e+24 // This big number is stored as a floating point?

I tried the string casting of x in Python, and it worked just fine, so I'm assuming this behavior is unique to JavaScript? I'm not too familiar with how JavaScript does things under the hood, so I was hoping I could get an explanation for what's going on here with JavaScript numbers and BigInt? And how would one store x and cast it into a string?

Thanks!

Jerryq27
  • 159
  • 1
  • 14
  • 1
    `This big number is stored as a floating point` all `Numbers` in javascript are so called "floating point" - integers greater than `Number.MAX_SAFE_INTEGER` are inaccurate, as you've found - `unique to JavaScript?` absolutely not - it's how *double-precision 64-bit binary format IEEE 754* works in C, C++, Fortran, Common List, Java, and Javascript to name just a few – Bravo Mar 06 '22 at 03:25
  • since `1000000000000000000000000000001` is about `100000000000000` times the maximum safe integer, what you get when converting to BigInt is practically random after about 16 digits or so ... note `BigInt("1000000000000000000000000000001")` works just fine though – Bravo Mar 06 '22 at 03:36
  • In JavaScript, `1000000000000000000000000000001n` (note trailing `n`) also creates a BigInt. In Python, `1000000000000000000000000000001.0` creates a 64-bit floating point number, which behaves like `1000000000000000000000000000001` in JavaScript. – jmrk Mar 06 '22 at 15:56

0 Answers0