1

As you can see below, in all the cases the number is shown wrong:

  var a = 714205074837649919;
  console.log(a); //>> 7.1420507483764992E17
  console.log(parseInt(a)); //>> 7.1420507483764992E17
  console.log(parseInt(a).toString()); //>> 714205074837649900
  console.log(parseFloat(a).toString()); //>> 714205074837649900
TheMaster
  • 45,448
  • 6
  • 62
  • 85
Bruno Yuzo
  • 469
  • 5
  • 18
  • What the question? – Cooper Jul 11 '20 at 17:31
  • 1
    Welcome to StackOverFlow please take this opportunity to take the [tour] and learn how to [ask], [format code](https://meta.stackexchange.com/questions/22186/how-do-i-format-my-code-blocks), [mcve] and [Tag Info](https://stackoverflow.com/tags/google-apps-script/info) – Cooper Jul 11 '20 at 17:39
  • Related: https://stackoverflow.com/q/9643626/1595451 – Rubén Jul 11 '20 at 18:06

1 Answers1

4

The Apps Script global environment includes BigInt.

Use strings, not numbers, to avoid rounding errors when providing a literal for the BigInt object.

function testBigInt() {
  const bigNumber = BigInt("714205074837649919");
  console.log(bigNumber.toString()); // 714205074837649919
}
dwmorrin
  • 2,704
  • 8
  • 17
  • To add to this, `n` notation: `1n` throws a syntax error: `Unexpected token ILLEGAL (line 5075, file "esprima.browser.js-bundle.js")` Someone should post a issue in the issuetracker; – TheMaster Jul 11 '20 at 18:51
  • 1
    Do you know why it rounds to 7142050748376499'20'? I need the exact number 7142050748376499'19' – Bruno Yuzo Jul 11 '20 at 18:52
  • @BrunoYuzo Conversion between number and bigint causes this. Change number to string: `const bigNumber = BigInt("714205074837649919");` – TheMaster Jul 11 '20 at 18:56
  • @BrunoYuzo yes, the number input can't work because it has the normal Number type limitations. Using a String bypasses the limitations of the Number type. – dwmorrin Jul 11 '20 at 19:20
  • 1
    The json value that I'm receiving is not a string, as you can see: `var JsonValue = JSON.parse('[{"GroupId":714205074837649919,"Type":"OrganisationGroup"}]'); console.log(JsonValue[0].GroupId); //7.1420507483764992E17` – Bruno Yuzo Jul 11 '20 at 20:39
  • 1
    @BrunoYuzo since you are receiving it that way, you might need to resort to using a RegExp to fix the JSON before parsing. See [this relevant stackoverflow question](https://stackoverflow.com/questions/20408537/parsing-big-numbers-in-json-to-strings). – dwmorrin Jul 11 '20 at 20:49