1

This may be a recurring question. I need to convert a string to an integer. But JS does this: parseInt("2166767952358020110") ⇒ 2166767952358020000

I know why it happens but how to correctly convert a string to an integer? BigInt() doesn't fit in my case.

Arthur
  • 3,056
  • 7
  • 31
  • 61
  • What about `BigInt("2166767952358020110")` ? – Nick Parsons Oct 31 '19 at 12:58
  • Does this answer your question? [How to convert strings to bigint in JavaScript](https://stackoverflow.com/questions/36826748/how-to-convert-strings-to-bigint-in-javascript) – Rojo Oct 31 '19 at 12:59
  • the number is too big... – Rojo Oct 31 '19 at 12:59
  • Ordinary numbers in JavaScript are always 64-bit floating-point values. The value Number.MAX_SAFE_INTEGER tells you the maximum integer value representable, and it's smaller than your value. In modern JavaScript environments you may be able to use `BigInt(yourString)` to make a "big integer" value. – Pointy Oct 31 '19 at 13:00
  • @NickParsons, in my case I can't use BigInt because it adds "n" at the end, but I need a normal integer – Arthur Oct 31 '19 at 13:03
  • 1
    There's a very famous implementation of Big Number in JS named "bn.js"... – tibetty Oct 31 '19 at 13:04

1 Answers1

1

As your number is above the Number.MAX_SAFE_INTEGER, you can't directly convert the string to a number without having some errors.

I suggest you to use the BigNumber library which has been done for this purpose

const BN = require('bn.js');

const number = new BN('2166767952358020110', 10);
oktapodia
  • 1,695
  • 1
  • 15
  • 31
  • Hi! Thanks for your answer, I tried your solution and it returns "1e11e7f8ff00140e".. Seems I can't get pure integer above 53 bites – Arthur Oct 31 '19 at 14:04
  • 1
    You will never have a pure integer above the limit but bignumber is providing you some helpers to perform the calculation you expect – oktapodia Oct 31 '19 at 21:02