-3

I want to convert a 17digit number string into a number this is the number "76561197962169398".I tried using parseInt() The result of using parseInt is :-

76561197962169390

I am loosing the last digit.I also tried BigInt() 'n' is getting appended to the number. I m thinking of using replace() with a regex for only digits.

Is there any other way I can achieve this without loosing precision. Please any help regarding this is really appriciated.THANK YOU

DeADLY
  • 69
  • 1
  • 6
  • `76561197962169398` is bigger than `Number.MAX_SAFE_INTEGER`. This will only work with `BigInt`; [What is JavaScript's highest integer value that a number can go to without losing precision?](https://stackoverflow.com/questions/307179/what-is-javascripts-highest-integer-value-that-a-number-can-go-to-without-losin) – Andreas Jun 28 '20 at 15:41
  • The problem with BigInt is that 'n' will get appended to the number – DeADLY Jun 28 '20 at 15:43
  • It "won't" because that's just how it is represented in strings or the console. – Andreas Jun 28 '20 at 15:44
  • Also, you don't have much of a choice. Anything greater than 2^53 - 1 must be represented using BigInt to avoid loss of precision. – JoshG Jun 28 '20 at 15:45
  • how can I remove that 'n' from the number – DeADLY Jun 28 '20 at 15:46
  • @DeADLY There's only a `n` when you "print" the number - either in the console or as a string which wouldn't make much sense when you just converted it from a string into a number :/ – Andreas Jun 28 '20 at 16:00
  • I want to sort the numbers when 'n' is present it is not possible right – DeADLY Jun 28 '20 at 16:05
  • There is NO `n`... :/ – Andreas Jun 28 '20 at 16:06

1 Answers1

1

in chrome 83 devtools:

x=76561197962169398n
76561197962169398n

++x
76561197962169399n

typeof x
"bigint"

y=BigInt("76561197962169398")
76561197962169398n

++y
76561197962169399n

x+y
153122395924338798n

x + 1
VM342:1 Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions
    at <anonymous>:1:2
(anonymous) @ VM342:1

x + 1n
76561197962169400n

[5n, 3n, 9n, 7n].sort()
[3n, 5n, 7n, 9n]

The n suffix is for display - and in code it's needed to say a literal value needs to be treated as bigint instead of number - think of it like quotes for strings - without quotes a sequence of characters is not a string - similarly a number without n suffix is not a bigint - it's a number that has limited precision and simply cannot be used for large values

Zartaj Majeed
  • 500
  • 2
  • 8