Search code examples
javascripthtmlnode.jsecmascript-6parseint

Bug when converting string to integer


Hey guys I have a problem with parsing Strings in Javascript. I have a big Number (162778063615164416) as a string. This is how a userID of discord looks like. Now I'm trying to convert it to a Number but it always returns the wrong value.

Run the Snippet to see it.

var qs = 'querySelector',
    qsa = 'querySelectorAll';
document[qs]('input').addEventListener('input', event => {
  var val = event.target.value;
  document[qsa]('td')[0][qs]('input').value = parseInt(val);
  document[qsa]('td')[1][qs]('input').value = Number(val);
  document[qsa]('td')[2][qs]('input').value = eval(val);
})
<table style="border: solid 1px">
  <thead>
    <tr>
      <th colspan="3"><input value="162778063615164416" style="width:98%; text-align: center"></th>
    </tr>
    <tr>
      <th>parseInt()</th>
      <th>Number()</th>
      <th>eval()</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input id="parse" style="text-align: center" value="162778063615164400" disabled></td>
      <td><input id="number" style="text-align: center" value="162778063615164400" disabled></td>
      <td><input id="eval" style="text-align: center" value="162778063615164400" disabled></td>
    </tr>
  </tbody>
</table>

I used three different methods to do the same thing and they all return wrong values. The output values should be the same as the input value. Anyone know, how to convert strings with this length to numbers?

I'm using the Discord API for Node.js to create a selfbot. The user send a message to a channel and the programm should read the userID to identify the only one person to which it should reply. I can't write the ID in the programm code, because its dynamic: I wanted to pack it into a .exe, that other people (people which don't know JavaScript or don't want to install Node.js) can use it too to send embeds and do other cool stuff.


Solution

  • According to the documentation.

    The MAX_SAFE_INTEGER constant has a value of 9007199254740991


    You should ask yourself why you are converting it to a number so. Do you want to compare them? You can compare Strings. You want to look for special values? You can use Regexp over Strings.