0

Can anybody explain why Number('31301006300002607') ( or parseInt('31301006300002607') ) returns 31301006300002610? Tried in Chrome and Firefox. Any implicit length restrictions?

Actually I need to validate up to 18-digits number along with truncating leading zeros but prefer to avoid regular expressions for such simple task.

Dmytro
  • 23
  • 5

2 Answers2

3

The Number.MAX_SAFE_INTEGER constant represents the maximum safe integer in JavaScript (253 - 1).

For larger integers, consider using BigInt.

source https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

kooskoos
  • 4,622
  • 1
  • 12
  • 29
0

You can't represent an 18-digit number as a number. The maximum safe value is:

console.log(Number.MAX_SAFE_INTEGER);

which is 16-digit. Any value above that number is unsafe and can cause various issues with your code so you definitely should represent such big numbers as strings in your case.

Sebastian Kaczmarek
  • 8,120
  • 4
  • 20
  • 38